Client:
PackageCn.zyw.javaurl;Importjava.io.IOException;Importjava.net.*;/*** Created by Zyw on 2016/4/2.*/ Public classUdpClient { Public Static voidMain (String args[]) {Try{datagramsocket Clientsocket=NewDatagramsocket (); String SendData= "Hello my name is Zyw"; byte[] bytes=senddata.getbytes (); InetAddress IP=inetaddress.getbyname ("127.0.0.1"); Datagrampacket Packet=NewDatagrampacket (Bytes,0,senddata.length (), ip,7777); Clientsocket.send (packet); bytedata[]=New byte[1024]; Datagrampacket Packet1=NewDatagrampacket (data,0, data.length); Clientsocket.receive (PACKET1); String s=NewString (data,0, Packet1.getlength ()); System.out.println ("Server say:" +s); } Catch(SocketException e) {e.printstacktrace (); } Catch(unknownhostexception e) {e.printstacktrace (); }Catch(IOException e) {e.printstacktrace (); } }}
Server:
PackageCn.zyw.javaurl;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;Importjava.net.SocketException;/*** Created by Zyw on 2016/4/2.*/ Public classUdpserver { Public Static voidMain (String args[]) {Try{datagramsocket ServerSocket=NewDatagramsocket (7777); byte[] Data=New byte[1024]; Datagrampacket Packet=NewDatagrampacket (data,data.length); System.out.println ("Server started ..."); Serversocket.receive (packet); String s=NewString (data,0, Packet.getlength ()); System.out.println ("Get client:" +s); Datagramsocket Clientsocket=NewDatagramsocket (); String SendData= "Welcome to you visit"; byte[] bytes=senddata.getbytes (); InetAddress IP=packet.getaddress (); intport=Packet.getport (); Datagrampacket P=NewDatagrampacket (bytes,0, Senddata.length (), ip,port); Clientsocket.send (P); } Catch(SocketException e) {e.printstacktrace (); }Catch(IOException e) {e.printstacktrace (); } }}
Java IO Review UDP