Udp
☆udp
Encapsulates data and sources and purposes into packets without establishing a connection
The size of each datagram is within the limit of 64k
Because there is no connection, it is an unreliable agreement.
No need to establish connection, fast speed
Datagramsocket and Datagrampacket class
☆tcp
Establish a connection to form a channel for transmitting data.
Make large data transfers in a connection
Complete connection via three handshake, is a reliable protocol
The connection must be established and the efficiency will be slightly lower
Sockets and ServerSocket Classes
☆socket
A socket is a mechanism that is provided for network services.
Sockets are available at both ends of the communication.
Network communication is actually the communication between sockets.
Data is transmitted via IO between two sockets.
UDP transport
Datagramsocket and Datagrampacket
Set up the sending side, the receiving end.
Set up the data package.
Invokes the Send receive method of the socket.
Close the socket.
The sending and receiving ends are two separate running programs.
UDP transmission Programming
☆ Sending End
On the sending side, specify the destination IP and port in the packet object.
new DatagramSocket();bytebynew DatagramPacket(by,0,by.length, InetAddress.getByName(“127.0.0.1”),10000);ds.send(dp);ds.close();
☆ Receiving End
On the receiving side, specify the port to listen on.
new DatagramSocket(10000);bytebynewbyte[1024new DatagramPacket(by,by.length);ds.receive(dp);StringnewString(dp.getData(),0,dp.getLength());System.out.println(str+"--"+dp.getAddress());ds.close();
Sender:
When you write your own, pay attention to modifying the receiver's IP.
PackageCN.HNCU.URL.UDP;ImportJava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;ImportJava.net.SocketException;/** * * @author Chen Haoxiang * * 2016-5-8 * * Public class senddemo { Public Static void Main(string[] args) {Try{Datagramsocket ds =NewDatagramsocket (9999);//Send a message with port 9999String str ="Hello, are you there?" ";byteBuf[] = str.getbytes ("GBK");in the//datagrampacket class, an IP address is constructed to create a send packet. Datagrampacket DP =NewDatagrampacket (buf, Buf.length,inetaddress.getbyname ("192.168.1.127"),10000);//Note: Both IP and port are receiver-sideDs.send (DP); Ds.close (); }Catch(SocketException e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); } }}
Receiving Party:
PackageCN.HNCU.URL.UDP;ImportJava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;ImportJava.net.SocketException; Public class receivedemo { Public Static void Main(string[] args) {Try{//Received PortDatagramsocket ds =NewDatagramsocket (10000);byteBuf[] =New byte[1024x768]; Datagrampacket DP =NewDatagrampacket (buf, buf.length); Ds.receive (DP);//Parse out the information we want from DP //Get IPString IP = dp.getaddress (). gethostaddress ();intPort = Dp.getport ();//Port byte[] data = Dp.getdata (); System.out.println ("IP:"+ip+"Port:"+port+"message:"+NewString (data)); }Catch(SocketException e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); } }}
Exercise: UDP Chat Program
Get the information you want to send via keyboard entry.
Package the send and receive separately into two threads.
Package Cn.hncu.url.udp;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; class udpchat { Public Static voidMain (string[] args) {Try{Datagramsocket send =NewDatagramsocket (10001); Datagramsocket receive =NewDatagramsocket (10000);NewThread (NewSend). Start ();NewThread (NewReceive). Start (); }Catch(SocketException e) {E.printstacktrace (); } }} class Send implements Runnable{Datagramsocket ds; PublicSend (Datagramsocket send) { This. ds=send; } @Override Public voidRun () {Datagrampacket dp; BufferedReader BFR =NewBufferedReader (NewInputStreamReader (system.in)); String Line; while(true){Try{line = Bfr.readline ();byte[] buf = Line.getbytes ();//Fill in the receiver's IP and portDP =NewDatagrampacket (buf, Buf.length, Inetaddress.getbyname ("192.168.1.127"),10000); Ds.send (DP);if("End". Equals (line)) { Break; } }Catch(IOException e) {E.printstacktrace (); }} ds.close (); }} class Receive implements Runnable{Datagramsocket ds; PublicReceive (Datagramsocket receive) { This. ds=receive; } @Override Public voidRun () {Datagrampacket dp;byte[] buf =New byte[2048];//size enough to save the data sent over one time. String Line; String IP;intPort while(true) {DP =NewDatagrampacket (buf, buf.length);Try{ds.receive (DP); }Catch(IOException e) {E.printstacktrace (); ip = dp.getaddress (). gethostaddress ();//Get the sender's IPPort = Dp.getport ();//Port byte[] bf = Dp.getdata (); line =NewString (BF,0, Dp.getlength ()); System.out.println ("IP:"+ip+"Port:"+port+"message:"+line);if("End". Equals (line)) {System.out.println ("Host:"+ip+"It's offline. "); Break; }} ds.close (); }}
Well, you can now realize the interaction of 2 networked machines. Ha ha
Just now it's a bit monotonous, and it's easy to drop packets with the UDP protocol.
Let's make progress together.
Java---Network programming (2)-UDP