是否可以使用单个 DatagramSocket 在单个 Java 应用程序中发送和接收数据包?我一直在尝试使用线程来做到这一点,但没有运气。我在网上找到的每个套接字教程都使用单独的客户端和服务器类来发送数据。但是,就我而言,我希望客户端和服务器驻留在一个应用程序中。以下是我的尝试:
public class Main implements Runnable {
// global variables
static DatagramSocket sock;
String globalAddress = "148.61.112.104";
int portNumber = 9876;
byte[] receiveData = new byte[1024];
public static void main(String[] args) throws IOException {
sock = new DatagramSocket();
(new Thread(new Main())).start();
// send data
while (true) {
InetAddress IPAddress = InetAddress.getByName("127.0.0.1");
int port = 9876;
int length = 1024;
byte [] sendData = new byte[1024];
String message = "hello";
sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, port);
sock.send(sendPacket);
}
}
public void run() {
//get incoming data
while (true) {
byte[] sendData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
receivePacket.setPort(portNumber);
try {
sock.receive(receivePacket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sentence = new String(receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
}
}
}
如您所见,我在主线程的循环中发送数据,并在可运行线程的循环中接收数据。主线程应该不断地向接收者发送“hello”并输出消息。但是,没有给出输出?
我在正确的轨道上吗?使用线程是最好的方法吗?这甚至可能吗?如果是这样,有更好的解决方案吗?