gpt4 book ai didi

Java UDP服务器

转载 作者:行者123 更新时间:2023-12-02 07:10:26 24 4
gpt4 key购买 nike

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

最佳答案

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

        serverSocket = new DatagramSocket(4722);

关于Java UDP服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15597492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com