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 に答える