while (true) { server.receive(packet); System.out.println("server has received data from sender"); StringdataStr=newString(data, 0, packet.getLength()); String[] dataSegments = dataStr.split(" "); if(dataSegments.length >= 2){ InetAddressreceiverAddress= InetAddress.getByName(dataSegments[0].split(":")[0]); intreceiverPort= Integer.parseInt(dataSegments[0].split(":")[1]); DatagramPackettrulyData=newDatagramPacket(dataSegments[1].getBytes(), dataSegments[1].length(), receiverAddress, receiverPort); System.out.println("the message: "+dataSegments[1]); server.send(trulyData); System.out.println("server has sent data to receiver"); } }
2. 客户端
客户端在创建时需指定端口号,这里使用命令行参数传入
1 2 3 4 5 6 7
publicclassClient { publicstaticvoidmain(String[] args)throws Exception { int port; if (args.length > 0) { port = Integer.parseInt(args[0]); DatagramSocketsocket=newDatagramSocket(port); System.out.println("client is ready!!");
创建接收消息的线程及发送消息的线程等待输入
1 2 3 4 5 6 7 8 9 10 11
// create a receiver thread ThreadreceiveThread=newThread(newReceiverRunnable(socket)); receiveThread.start(); // receive message at any time // create a sender thread ThreadsendThread=newThread(newClientSenderRunnable(socket)); sendThread.start(); }else{ System.out.println("you must indicate the port by adding argument"); } } }
@Override publicvoidrun() { System.out.println("type as (address:port message):"); Scannerscanner=newScanner(System.in); String dataStr; if (scanner.hasNextLine()) { dataStr = scanner.nextLine(); System.out.println("your header and message: " + dataStr); byte[] data = dataStr.getBytes();
根据静态变量指定的服务端地址打包数据报并发送
1 2 3 4 5 6 7 8 9 10 11 12 13
// pack up the data try { InetAddressserverAddress= InetAddress.getByName(serverName); DatagramPacketpacket=newDatagramPacket(data, data.length, serverAddress, serverPort); // create socket and send data packed socket.send(packet); System.out.println("client has sent data to server!!"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }