我写了一个小型客户端 - 服务器应用程序。它应该从客户端发送一个字符串到服务器,服务器应该在控制台上显示它。但是服务器一直在等待数据。看起来数据不会来到服务器。我错了什么?
public class UDPClient {
public static void main(String[] args) throws IOException {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAdress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAdress, 4445);
clientSocket.close();
}
}
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket serverSocket = new DatagramSocket(4445);
byte[] receiveData = new byte[1024];
while(true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
}
}
}
答案 0 :(得分:0)
你忘了实际通过套接字发送包。
只需添加
clientSocket.send(sendPacket);
之前
clientSocket.close();
在UDPClient.main()
中,一切都会有效。