我的 UDP 客户端会不断发送“Hello Server!” 每 2 秒发送到 UDP 服务器(只是回显消息,但以大写形式)。他们都会打印收到的内容。
我的问题是我总是必须先运行服务器然后再运行客户端。如果我运行客户端然后服务器,服务器将不会收到任何东西。我希望服务器在他想要的任何时候启动并且仍然从客户端接收数据包。我怎样才能做到这一点?
UDP客户端:
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
while(true) {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[100];
byte[] receiveData = new byte[100];
String sentence = "Hello Server!";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
Thread.sleep(2000);
}
}
}
UDP服务器:
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[100];
byte[] sendData = new byte[100];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}