Summary: Test on the same host, same IP address, different ports, use UDP to receive data
Using socket programming to send data over the UDP protocol
Requirement: Send a single piece of data to a port on an IP using the UDP protocol
Udpsend.java
Packagecom. Train;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;Importjava.net.SocketException;Importjava.net.UnknownHostException;//UDP Transport:/**Step:---* 1, establish UDP socket receive and send point * 2, provide data, package * 3, send using Send * 4, close resources **/ Public classUdpsend { Public Static voidMain (string[] args)throwsSocketException, unknownhostexception {/**1. Set up UDP socket endpoint*/Datagramsocket S=NewDatagramsocket (); /**2, provide data, packaging packaging---datagrampacket (byte[] buf, int length, inetaddress address, int port)*/ byte[] bs = "Sending with UDP-I'm data!". GetBytes (); Datagrampacket DP=NewDatagrampacket (BS, Bs.length, Inetaddress.getbyname ("192.168.1.189"), 8070); /**3. Sending using send*/ Try{S.send (DP); } Catch(IOException e) {System.out.println ("Send failed:"); E.printstacktrace (); } /**4. Close Resources*/S.close (); }}
Run the above Java program:
Get the data in the Network Data Transceiver tool:
Using socket programming to receive data over the UDP protocol
Udprecv.java
Packagecom. Train;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;//UDP Transport: receiving/**Step:---* 1, establish a UDP socket, set the Receive Port * 2, pre-create the location of data storage, Package * 3, use receive blocking receive * 4, close resources **/ Public classUDPRECV { Public Static voidMain (string[] args)throwsexception{/**1. Set up a UDP socket, setting the receive Port*/datagramsocket DS=NewDatagramsocket (3020); /**2, pre-create the location of data storage, packaging*/ byte[] Bbuf =New byte[1024]; Datagrampacket DP=NewDatagrampacket (bbuf,bbuf.length); /**3. Using Receive-blocking*/Ds.receive (DP); System.out.println ("IP::" +dp.getaddress (). Gethostaddress () + "\nport::" +dp.getport () + "\ndata::" +NewString (Dp.getdata ())); /**4. Close Resources*/Ds.close (); }}
Test steps:
1. After running the Udprecv.java program, observe the output of the console: none
2, using the Network Transceiver tool, through the UDP protocol to 3020 port to send data, click Send:
3, Eclipse<console>:
Java Basic-socket programming-udp sending and receiving