0

我是 Java 编程新手,我正在尝试创建一个 UDP 服务器。当我编译代码时,它说它无法监听端口 4722,我想知道为什么。下面是代码。我将不胜感激任何建议。

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();
}
}
4

2 回答 2

2

您正在初始化serverSocket,然后DatagramSocket再次在同一个端口上创建一个新端口(您不能这样做,因为它已经绑定在第一个端口上DatagramSocket)。即删除以下行:

        serverSocket = new DatagramSocket(4722);
于 2013-03-24T11:42:57.363 回答
0

这是客户端/服务器 UDP 通信的完整示例。

服务器从文件中读取数据并将每一行发送到客户端。

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();
    }
}

}

如果您的文件包含:

Hello
World

你应该看到:

Waiting for packet...
Sending : Hello
Received : HelloWaiting for packet...
Sending : World
Received : World
Waiting for packet...
于 2017-02-24T23:43:03.190 回答