1.UDP definition
UDP is also called user data protocol [connectionless protocol]
Advantages: the safety and reliability of data cannot be guaranteed
Disadvantages: low consumption and high efficiency
2. Classes and methods required by UDP based network communication program
UDP based network communication program does not distinguish between client and server.
(1) Java.net.datagram packet [only responsible for creating packets for sending and packets for receiving]
This class represents a datagram packet. [package sent data / receive sent data]
Construction method: used to package
DatagramPacket(byte[] buf, int length) construct a datagram packet to receive the length of the packet. [data packet receiving incoming data]
DatagramPacket(byte[] buf, int length, InetAddress address, int Port [port number of the receiver]) constructs a datagram for sending packets of length. The packet length is from the specified host to the specified port number. [package sent data]
Instance method: used to parse
byte[] getData() returns the data buffer.
int getLength() returns the length of the data to be sent or received.
InetAddress getAddress() returns the IP address of the computer that sent or received the datagram.
int getPort() returns the port number on the remote host from which the datagram was sent or received. [get the port number of the sender]
(2) Java.net.datagram socket [responsible for sending and receiving packets]
This class represents the socket used to send and receive datagram packets.
Construction method:
Datagram socket() constructs a datagram socket and binds it to any available port on the local host. [Employer]
DatagramSocket(int port) constructs a datagram socket and binds it to the specified port on the local host. [package receiving]
Instance method:
void send(DatagramPacket p) Send datagram packets from this socket.
void receive(DatagramPacket p) Receive datagram packets from this socket.
void close() closes the datagram socket.
3. Creation steps of communication program based on UDP protocol
(1) Sender:
- Send the data to be sent through datagram packet (byte [] buf, int length, InetAddress address, int port) the construction method is packaged.
- Create a DatagramSocket object through the construction method of DatagramSocket().
- The send method of the datagram socket object sends the packed datagram packet.
- Close datagram socket.
(2) Receiver:
- Through DatagramSocket(int) port) create a DatagramSocket object to receive data.
- Through datagram packet (byte []) buf, int length) creates an empty datagram packet.
- Receive datagram packets into empty datagram packets by calling the receive method of the datagram socket object receiving data.
- Parse datagram packets.
- Close datagram socket.
4. Code demonstration
4.1 client sends and server receives
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class ClientSendMain { public static void main(String[] args) throws Exception{ //Define datagram packet DatagramPacket sendpacket=null; InetAddress receiveaddress=null; int port=3000; BufferedReader buff=null; DatagramSocket sendsocket=null; /* * Create a package to send - data packaging - send */ //Keyboard input data ---- data to be sent System.out.println("Please enter the data to be sent:"); buff=new BufferedReader(new InputStreamReader(System.in)); String info = buff.readLine(); byte[] bytes = info.getBytes(); int length=bytes.length; //Local address receiveaddress=InetAddress.getLocalHost(); //Create a send packet with a server address and port number sendpacket=new DatagramPacket(bytes, length, receiveaddress, port); //Create DatagramSocket object sendsocket=new DatagramSocket(); sendsocket.send(sendpacket); sendsocket.close(); } }
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class ServerMain { public static void main(String[] args) throws Exception { /* * Create receiving object - create an empty datagram packet for receiving - parse */ //Create the object to receive the package int port=3000; DatagramSocket receivesocket = new DatagramSocket(port); //Create an empty datagram packet byte buff[]=new byte[1024]; DatagramPacket receivepacket = new DatagramPacket(buff, buff.length); //receive data receivesocket.receive(receivepacket); //Parse data byte data[] = receivepacket.getData(); int len=receivepacket.getLength(); String msg=new String(data,0,len); String clientip = receivepacket.getAddress().getHostAddress(); int clientsendport = receivepacket.getPort(); System.out.println("Received from"+clientip+":"+clientsendport+"News of:"+msg); receivesocket.close(); } }
4.2 the client keeps sending and the server keeps receiving
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class ClientSendMain { public static void main(String[] args) throws Exception { BufferedReader buff = null; InetAddress receiveaddress = null; int serverport = 3000; DatagramPacket sendpacket = null; DatagramSocket sendsocket = null; buff = new BufferedReader(new InputStreamReader(System.in)); sendsocket = new DatagramSocket(); receiveaddress = InetAddress.getLocalHost(); boolean flag = true; while (flag) { System.out.println("Please enter the data to be sent:"); String sendinfo = buff.readLine(); sendpacket = new DatagramPacket(sendinfo.getBytes(), sendinfo.getBytes().length, receiveaddress, serverport); sendsocket.send(sendpacket); if (sendinfo.equals("exit")) { flag=false; } } sendsocket.close(); } }
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class ServerMain { public static void main(String[] args) throws Exception { DatagramSocket receivesocket = null; DatagramPacket receivepacket = null; String receivemsg = null; int serverport = 3000; String clientip = null; int clientsendport = 0; boolean flag = true; receivesocket = new DatagramSocket(serverport); byte buff[] = new byte[1024]; receivepacket = new DatagramPacket(buff, buff.length); while (flag) { receivesocket.receive(receivepacket); byte data[] = receivepacket.getData(); int len = receivepacket.getLength(); receivemsg = new String(data, 0, len); clientip = receivepacket.getAddress().getHostAddress(); clientsendport = receivepacket.getPort(); System.out.println("Server received from" + clientip + ":" + clientsendport + "News of:" + receivemsg); if(receivemsg.equals("exit")){ flag=false; } } receivesocket.close(); } }
4.3 two way - the client continuously sends and receives, and the server continuously receives and sends
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class ClientSendMain { public static void main(String[] args) throws Exception { //The client sends the required variables and objects BufferedReader buff = null; InetAddress receiveaddress = null; int serverport = 3000; DatagramPacket sendpacket = null; DatagramSocket sendsocket = null; buff = new BufferedReader(new InputStreamReader(System.in)); sendsocket = new DatagramSocket(); receiveaddress = InetAddress.getLocalHost(); //The client receives the required variables and objects DatagramPacket receivepacket=null; DatagramSocket receivesocket=null; int receiveport=2000; receivesocket=new DatagramSocket(receiveport); byte bys[]=new byte[1024]; receivepacket=new DatagramPacket(bys,bys.length); boolean flag = true; while (flag) { //hair System.out.println("Please enter the data to be sent:"); String sendinfo = buff.readLine(); sendpacket = new DatagramPacket(sendinfo.getBytes(), sendinfo.getBytes().length, receiveaddress, serverport); sendsocket.send(sendpacket); //collect receivesocket.receive(receivepacket); String receivemsg = new String( receivepacket.getData(), 0, receivepacket.getLength()); System.out.println("Received data returned from the server---"+receivemsg); if (receivemsg.equals("exit")) { flag=false; } } sendsocket.close(); receivesocket.close(); } }
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class ServerMain { public static void main(String[] args) throws Exception { System.out.println("Server started...."); //Server collection DatagramSocket receivesocket = null; DatagramPacket receivepacket = null; int serverport = 3000; receivesocket = new DatagramSocket(serverport); byte buff[] = new byte[1024]; receivepacket = new DatagramPacket(buff, buff.length); //Server send DatagramPacket sendpacket = null; DatagramSocket sendsocket = null; int sendport=2000; InetAddress receiveaddress = InetAddress.getLocalHost(); sendsocket=new DatagramSocket(); boolean flag = true; while (flag) { //collect receivesocket.receive(receivepacket); byte data[] = receivepacket.getData(); int len = receivepacket.getLength(); String receivemsg = new String(data, 0, len); String clientip = receivepacket.getAddress().getHostAddress(); int clientsendport = receivepacket.getPort(); System.out.println("Server received from" + clientip + ":" + clientsendport + "News of:" + receivemsg); //hair sendpacket=new DatagramPacket(receivemsg.getBytes(),receivemsg.getBytes().length,receiveaddress,sendport); sendsocket.send(sendpacket); if(receivemsg.equals("exit")){ flag=false; } } sendsocket.close(); receivesocket.close(); } }
4.4 multiple clients continuously send and receive, and servers continuously send and receive
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.Scanner; /** * Client sending data * * */ public class Client { public static void main(String[] args) throws Exception { BufferedReader buff = new BufferedReader(new InputStreamReader(System.in)); //Bind a specified port to receive and send data DatagramSocket server=new DatagramSocket(); //Define an empty packet to receive data byte[] sbyte=new byte[1024]; DatagramPacket spack=new DatagramPacket(sbyte, sbyte.length); //Defines a loop variable that continuously controls transmission boolean flag=true; while (flag) { System.out.println("Please enter the data to send:"); String info=buff.readLine(); //Package data byte[] fbyte=info.getBytes(); DatagramPacket fpack=new DatagramPacket(fbyte, fbyte.length, InetAddress.getLocalHost(), 3000); //send data server.send(fpack); //Judge exit if (info.equals("886")) { flag=false; System.out.println("Close the client!"); }else{ //receive data server.receive(spack); //Unpacking byte data[]=spack.getData(); String msg=new String(data,0,spack.getLength()); System.out.println("The data returned by the received server is:"+msg); } } server.close(); } }
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /** * Server side receiving data * * */ public class Server { public static void main(String[] args) throws Exception { //Bind the port to receive data DatagramSocket server=new DatagramSocket(3000); System.out.println("---->The server has started, waiting for the client to send data"); byte[] bytes = new byte[1024]; while(true){ DatagramPacket packet = new DatagramPacket(bytes, bytes.length); server.receive(packet); ClientThread clientThread=new ClientThread(server,packet); Thread th=new Thread(clientThread); th.start(); } } }
/** * User sending data thread class * */ import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class ClientThread implements Runnable{ private DatagramSocket server; private DatagramPacket datagramPacket; private boolean falg=true; public ClientThread(DatagramSocket server,DatagramPacket datagramPacket ) { this.server=server; this.datagramPacket=datagramPacket; } public void run() { try{ while(falg){ //Unpacking byte data[]=datagramPacket.getData(); int len=datagramPacket.getLength(); String info=new String(data,0,len); String clientip = datagramPacket.getAddress().getHostAddress(); int clientsendport = datagramPacket.getPort(); System.out.println("Server received from" + clientip + ":" + clientsendport + "News of:" + info); //Judge exit if (info.equals("886")) { falg=false; //server.close(); System.out.println("Client exit"); }else{ //send data info="server: "+info; byte fbyte[]=info.getBytes(); DatagramPacket fPacket=new DatagramPacket(fbyte, fbyte.length,datagramPacket.getAddress(),datagramPacket.getPort()); server.send(fPacket); falg=false; } } //close }catch(Exception e){ e.printStackTrace(); } } }