[英]How to have UDP Server and Client simultaneously listening for incoming and outgoing packets
我正在尝试在 Java 中实现一个简单的 UDP 连接,并且我希望客户端和服务器都在监听传入消息并准备同时发送消息。
目前,该程序使得服务器开始侦听传入的数据包,以便客户端发送第一条消息。
如果可能的话,我真的很想知道一种简单的方法来实现这一点。
这是客户端的代码:
class EchoClient
{
public static void main( String args[] ) throws Exception
{
System.out.println("\nWelcome to UDP Client");
System.out.println("---------------------------------------------------");
Scanner sc = new Scanner (System.in);
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(120000);
while (true)
{
//Send
System.out.print("\nEnter message: ");
String msg = sc.nextLine();
byte[] buffer = msg.getBytes();
DatagramPacket packetS = new DatagramPacket(buffer,buffer.length,InetAddress.getByName(args[0]),1500);
socket.send( packetS );
//Receive
DatagramPacket packetR = new DatagramPacket(new byte[512],512);
socket.receive( packetR );
System.out.println( "Alice at: "+new Date()+" "+packetR.getAddress()+":"+packetR.getPort()+"\nSays: "+new String(packetR.getData(),0,packetR.getLength()) );
}
}
}
服务器的代码:
class EchoServer
{
public static void main( String args[] ) throws Exception
{
System.out.println("\nWelcome to UDP Server");
System.out.println("---------------------------------------------------");
Scanner sc = new Scanner (System.in);
DatagramSocket socket = new DatagramSocket(1500);
//Message loop
while ( true )
{
//Receiving
DatagramPacket packetR = new DatagramPacket(new byte[512],512);
socket.receive( packetR );
System.out.println("Bob at: "+new Date()+" "+packetR.getAddress()+":"+packetR.getPort()+"\nSays: "+new String(packetR.getData(),0,packetR.getLength()) );
//Send
System.out.print("\nEnter message: ");
String msg = sc.nextLine();
byte[] buffer = msg.getBytes();
DatagramPacket packetS = new DatagramPacket(buffer,buffer.length,packetU.getAddress(),packetU.getPort());
socket.send( packetS );
}
}
}
您好,这样做的一种简单方法是在主线程中启动多个线程。
class EchoServerClient
{
public static void main( String args[] ) throws Exception
{
new Thread(() -> {
EchoServer.main(args) //You can also rename main by another name
}).start();
new Thread(() -> {
EchoClient.main(args) //You can also rename main by another name
}).start();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.