Java UDP 服务器
我是 Java 编程新手,我正在尝试创建一个 UDP 服务器.当我编译代码时,它说它无法监听端口 4722,我想知道为什么.下面是代码.如有任何建议,我将不胜感激.
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();
}
}
推荐答案
你正在初始化 serverSocket
然后再次在同一个端口上创建一个新的 DatagramSocket
(你可以'不要这样做,因为它已经绑定在第一个 DatagramSocket
上).IE.删除以下行:
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);
相关文章