Java UDP server

2019-03-03 22:40发布

I am new to Java programming and I am trying to create a UDP server. When I compile the code it says it could not listen to port 4722 and I would like to know why. Below is the code. I would be grateful for any advice.

import java.net.*;
import java.io.*;


public class Server 
{
public static void main(String[] args) throws IOException 
{
    DatagramSocket serverSocket = new DatagramSocket(4722);
    Socket clientSocket = null;
    byte[] receiveData = new byte[1024];
    byte[] sendData = new byte [1024];      

    boolean command = true;
        try
        {
            serverSocket = new DatagramSocket(4722);
            DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
            System.out.println("Waiting for client...");


        } 


        catch (IOException e) 
        {
            System.err.println("Could not listen on port: 4722.");
            System.exit(1);

        }
        DatagramPacket packet = new DatagramPacket (sendData,sendData.length,4722);
        serverSocket.send(packet);



        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine, outputLine;
        mathematicalProtocol bbm = new mathematicalProtocol();

        outputLine = bbm.processInput(null);
        out.println(outputLine);

        while ((inputLine = in.readLine()) != null) 
        {
            if(inputLine.equals("Bye."))
            break;
            outputLine = bbm.processInput(inputLine);
            out.println(outputLine);
            if (outputLine.equals("Bye."))

            break;
        }

        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
}
}

标签: java udp
2条回答
戒情不戒烟
2楼-- · 2019-03-03 23:22

You are initializing serverSocket and then making a new DatagramSocket on the same port again (and you can't do that as it's already bound on the first DatagramSocket). I.e. remove the following line:

        serverSocket = new DatagramSocket(4722);
查看更多
仙女界的扛把子
3楼-- · 2019-03-03 23:31

Here is a complete example of client/server UDP communication.

The server read data from a file and send each line to the client.

import java.io.BufferedReader; 
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author nono
 *
 */

public class UDPFileSender {

static class Client implements Runnable {

    // Reception socket
    private DatagramSocket socket;
    // UDP packet to receive data into
    private DatagramPacket packet;
    // Flag for initialisation
    private boolean failedInit = true;

    /**
     * Client constructor.
     * @param receptionPort
     * @param packetMaxLenght
     */
    public Client(int receptionPort, int packetMaxLenght) {
        try {
            // Create the socket using the reception port
            this.socket = new DatagramSocket(receptionPort);
            // Init the packet
            this.packet = new DatagramPacket(new byte[packetMaxLenght],packetMaxLenght);
            this.failedInit = false;
        } catch (SocketException e) {
            //Port already used or other error
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        if(failedInit){
            return;
        }
        // Loop undefinitly
        while(true){
            try {

                System.out.println("Waiting for packet...");

                // Wait for packet
                socket.receive(packet);

                // Assuming you are receiving string
                String msg = new String(packet.getData());
                System.out.println("Received : " + msg);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

public static void main(String[] args) {

    try {

        int port = 4722;

        //Start a client that can listen
        new Thread(new Client(port,1024)).start();

        // Creaete a reader
        BufferedReader reader = new BufferedReader(new FileReader("File.txt"));

        //Create a socket
        DatagramSocket socket = new DatagramSocket();

        // Create a packet
        byte[] data = new byte[1024]; // Max length
        DatagramPacket packet = new DatagramPacket(data, data.length);

        // Set the destination host and port 
        packet.setAddress(InetAddress.getByName("localhost"));
        packet.setPort(port);

        String line = null;
        while((line = reader.readLine()) != null){
            //Set the data
            packet.setData(line.getBytes());

            //Send the packet using the socket
            System.out.println("Sending : " + line);
            socket.send(packet);
            Thread.sleep(200);
        }

        //Close socket and file
        reader.close();
        socket.close();

    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

}

If your file contains :

Hello
World

You should see :

Waiting for packet...
Sending : Hello
Received : HelloWaiting for packet...
Sending : World
Received : World
Waiting for packet...
查看更多
登录 后发表回答