Java Datagrampacket datagramsocket和线程

时间:2013-05-16 11:47:24

标签: java network-programming datagram

修改下面的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();
}

我做得对吗还是应该这样做?我的意思是,还有更好的方法吗?提前谢谢。

0 个答案:

没有答案