1. Client code
1 Importjava.io.IOException;2 ImportJava.net.DatagramPacket;3 ImportJava.net.DatagramSocket;4 Importjava.net.InetAddress;5 6 Public classUdpClient {7 Public Static voidMain (string[] args)throwsIOException {8 //1. Define the server's address, port number, data9InetAddress address = Inetaddress.getbyname ("localhost");Ten intPort = 8800; One byte[] data = "User name: admin; Password: 123 ". GetBytes (); A //2. Create a datagram that contains the sent data information -Datagrampacket packet =Newdatagrampacket (data, data.length,address,port); - //3. Create a Datagramsocket object theDatagramsocket socket =NewDatagramsocket (); - //4. Sending datagrams to the server side - socket.send (packet); - /** + * Receive server-side response data - */ + //1. Create datagrams to receive data from server-side responses A byte[] Data2 =New byte[1024]; atDatagrampacket Packet2 =NewDatagrampacket (data2, data2.length); - //2. Receiving server response data - socket.receive (Packet2); - //3. Reading data -String reply =NewString (data2, 0, Packet2.getlength ()); -System.out.println ("I am the client, I received the server information:" +reply); in //4. Close Resources - socket.close (); to } +}View Code
2. Server-side code
1 Importjava.io.IOException;2 ImportJava.net.DatagramPacket;3 ImportJava.net.DatagramSocket;4 Importjava.net.InetAddress;5 /**6 * 7 * UDP Server side8 *9 */Ten Public classUdpserver { One Public Static voidMain (string[] args)throwsIOException { A //1. Create a server-side datagramsocket, specify the port -Datagramsocket socket =NewDatagramsocket (8800); - //2. Create a datagram to receive data sent by the client the byte[] data =New byte[1024];//creates a byte array that specifies the size of the received packet. -Datagrampacket packet =Newdatagrampacket (data, data.length); - //3. Receiving data sent by the client -SYSTEM.OUT.PRINTLN ("* * * Server has been started, waiting for client to send information"); +Socket.receive (packet);//This method will block until the datagram is received - //4. Reading data +String info =NewString (data, 0, Packet.getlength ()); ASystem.out.println ("I am the server, the client says:" +info); at - /** - * Response data to the client - */ - //1. Define the client's address, port number, data -InetAddress address =packet.getaddress (); in intPort =Packet.getport (); - byte[] Data2 = "Welcome you!" ". GetBytes (); to //Send data to client +Datagrampacket Packet2 =NewDatagrampacket (data2, data2.length,address,port); - socket.send (Packet2); the //4. Close the socket * socket.close (); $ }Panax Notoginseng}View Code
Java UDP Programming