PackageCom.socket;ImportJava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;ImportJava.net.SocketException;ImportJava.net.UnknownHostException;/** * Requirements: via UDP transmission, send a piece of text * 1, establish udpscoket service * 2, provide data, package data into the packet * 3, through the socket send function, the data packets send out * 4, close the resources * * */ Public class udpsend { Public Static void Main(string[] args)throwsIOException {///1, create socket object, through Datagramsocket objectDatagramsocket ds =NewDatagramsocket ();///2, determine data, and package into a packet byte[] data ="Hello World". GetBytes (); Datagrampacket DP =NewDatagrampacket (data, Data.length, Inetaddress.getbyname ("localhost"),8801);//3, through the Scoket service, the existing data sent out through the Send methodDs.send (DP); Ds.close (); }}
PackageCom.socket;ImportJava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;/** * Requirements: Define an English program that accepts data transmitted by the UDP protocol and processes * * 1, defining the Uspsocket service. Usually listen to a port, in fact, to this network application to define the digital ID, * Easy to identify what data come over the application can process. * 2, define a packet, because the received byte data is to be stored. Because there are more features in the packet object * You can extract different data information from the byte data. * 3, through the socket service receive method, the received data into the defined data package * 4, the packet object unique features, the different data out * 5, close the resource **/ Public class udprece { Public Static void Main(string[] args)throwsioexception{System.out.println ("===========================");///1, create a UDP socket, establish an endpoint, and specify a fixed portDatagramsocket ds =NewDatagramsocket (8801);///2, define a packet for storing data byte[] buf =New byte[1024x768]; Datagrampacket DP =NewDatagrampacket (buf, buf.length);//3, receive the data and deposit it into the packet via the Receive method of the serviceDs.receive (DP);///4. Get the data in the data packet by means of the method. String IP = dp.getaddress (). gethostaddress ();intPort = Dp.getport (); String data =NewString (Dp.getdata (),0, Dp.getlength ()); System.out.println ("IP ="+ IP +": "+ Port +": "+ data);//Close ResourcesDs.close (); }}
JAVA--UDP Sending and receiving data