修改下面的 UDP 客户端程序,以便在允许输入姓氏和名字后,它会创建一个线程来构建消息,发送到服务器并等待回复。
public static void main(String[] args) {
DatagramSocket aSocket = null;
try {
Scanner input=new Scanner(System.in);
aSocket = new DatagramSocket(); // any port
System.out.println("Input Surname");
String Surname=input.nextLine();
System.out.println("Input First Name");
String Fname=input.nextLine();
String message=Surname + "," + Fname;
byte [] m = message.getBytes();
InetAddress aHost = InetAddress.getByName("localhost");
int serverPort = 6789;
DatagramPacket request = new DatagramPacket(m, message.length(), aHost,
serverPort);
aSocket.send(request);
aSocket.close();
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e){System.out.println("IO: " + e.getMessage());}
}
在我的一堂课中,我把上面的问题作为练习,我做了如下:
public static void main(String[] args) {
Runnable r2 = new Runnable() {
public void run() {
try {
DatagramSocket aSocket = new DatagramSocket();
String myMessage = "Hello World this is me";
byte[] b = myMessage.getBytes();
InetAddress host = InetAddress.getByName("localhost");
int port = 6789;
DatagramPacket request = new DatagramPacket(b, b.length, host, port);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println("received: " + new String(reply.getData()));
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread t2 = new Thread(r2);
t2.start();
}
我做得对还是应该以任何方式完成?我的意思是有没有更好的方法来做到这一点?提前致谢。