客户端接收用户在控制台上的输入,然后调用 DatagramSocket 中的send方法, 将数据传递出去.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class UDPDiscardClient { public final static int DEFAULT_PORT = 9 ; /** *//** * @param args */ public static void main(String[] args) { String hostname = null; int port = DEFAULT_PORT ; if(args.length > 0) { hostname = args[0] ; port = Integer.parseInt(args[1]) ; } try { InetAddress server = InetAddress.getByName(hostname) ; BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in)) ; DatagramSocket theSocket = new DatagramSocket() ; while(true) { String theLine = userInput.readLine() ; if(theLine.equals(".")) break ; byte [] data = theLine.getBytes("UTF-8") ; DatagramPacket theOutput = new DatagramPacket(data , data.length , server , port) ; theSocket.send(theOutput) ; } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UDPDiscardServer { public final static int DEFAULT_PORT = 9 ; public final static int MAX_PACKET_SIZE = 65507 ; /** *//** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int port = DEFAULT_PORT ; byte [] buffer = new byte[MAX_PACKET_SIZE] ; port = Integer.parseInt(args[0]) ; try { DatagramSocket server = new DatagramSocket(port) ; DatagramPacket packet = new DatagramPacket(buffer , buffer.length) ; while(true) { server.receive(packet) ; String s = new String(packet.getData() , 0 , packet.getLength() ,"UTF-8") ; System.out.println(packet.getAddress() + "at port " + packet.getPort() +"says"+ s); /**//*必须重新设置*/ packet.setLength(buffer.length) ; } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }