In the previous article, the Java SOCKET+TCP/IP protocol was used to implement real-time bidirectional communication between the application or client-server, and in this article, the UDP protocol was used to implement the Socket communication.
1. About UDP
UDP protocol (User Datagram Protocol) is non-connected, unreliable, unordered, fast, for data transmission, the first data to be transmitted is defined as a datagram (Datagram), the size is limited to 64k, in the datagram indicates the data requested to reach the socket (host address and port number), Then send the datagram, Java to the UDP protocol communication provides two main classes, Datagrampacket class: Represents the datagram packet, Datagramsocket class: The end-to-end communication class.
2. Implementation methods
2.1 Server-side
- Create Datagramsocket, specify port number
- Create Datagrampacket
- Accept data sent by the client
- Reading data
Server-side, implement UDP-based user login//1, create server-side datagramsocket, specify port datagramsocket socket =new Datagramsocket (10010); 2. Create a datagram to accept data sent by the client byte[] data =newbyte[1024];//datagrampacket packet =newdatagrampacket (data,data.length); 3, accept the data sent by the client socket.receive (packet);//This method will be consistent block//4, read data String info =newstring (data,o,data.length) before accepting datagrams; System.out.println ("Hello, I am the server, the client told me" +info);
2.2 client
- Defining sending information
- Create a datagrampacket that contains the information that will be sent
- Create Datagramsocket
- Send data
Client//1, define the server's address, port number, data inetaddress addresses =inetaddress.getbyname ("localhost"); int port = 10010; byte[] data = "Username: admin; password: 123". GetBytes (); 2, create the datagram, contains the data sent Datagrampacket packet = Newdatagrampacket (data,data,length,address,port); 3, create Datagramsocket object Datagramsocket socket =newdatagramsocket (); 4, send data to the server socket.send (packet);
3. Attention Issues
- Multithreading priority problem: according to the actual experience, the appropriate reduction of priority, the non-side may have a program running low efficiency situation
- Whether to close the output stream and input stream: for the same socket, if the output stream is turned off, the socket associated with the output stream will also be closed, so it is generally not necessary to close the stream and close the socket directly
- transferring objects using TCP Communication, serialization portion of IO
- Socket programming transfer file, IO Stream section
References :
Http://www.cnblogs.com/linzheng/archive/2011/01/23/1942328.html
JAVA Socket Programming Learning Note (ii)