1. An overview of the

Use DatagramSocket and DatagramPacket to achieve UDP communication. UDP is relatively simpler than TCP. There is no need to wait for a connection, and DatagramPacket is only needed for processing data without using output stream. Strictly speaking,UDP does not have a server and a client, only a sender and a receiver.

2. The sender

The sender establishes the DatagramSocket and DatagramPacket, sets the port and IP address of the DatagramPacket, and sends the packet through the DatagramSocket.

(1) Create DatagramSocket and DatagramPacket

DatagramSocket socket = new DatagramSocket(55555);
Copy the code

Port 55555 here is the port through which data is sent.

(2) create DatagramPacket

InetAddress ip = InetAddress.getByName("127.0.0.1");
int port = 12345;
String message = "message";
DatagramPacket packet = new DatagramPacket(message.getBytes(),message.getBytes().length,ip,port);
Copy the code

The four parameters of the constructor DatagramPacket() are respectively

  • An array of bytes sent
  • Byte array length
  • ip
  • port

The port must be different from the preceding one; otherwise, a message is displayed indicating that the port is occupied.

(3)

socket.send(packet);
Copy the code

3. The receiver

The receiver only needs to specify the port to receive the packet, which is specified in the constructor of the DatagramSocket and is the same as that set in the packet sent by the sender.

(1) create DatagramSocket

DatagramSocket socket = new DatagramSocket(12345);
Copy the code

(2) create DatagramPacket

The DatagramPacket created here only needs to specify the byte array to store the data and the length of that byte array.

byte [] message = new byte[2048];
DatagramPacket packet = new DatagramPacket(message, message.length);
Copy the code

(3) receiving

socket.receive(packet);
Copy the code

This method blocks until a packet is received.

(4) Data acquisition

After receiving the packet, we can use getData() to get the data and return an array of bytes, which can be passed to the String constructor to create a String.

String str = new String(packet.getData());
Copy the code

4. Complete code

Here, the client and the server are artificially set to send data to each other. The server sends input to the server, and the server returns fixed data. The “client” and “server” take turns to play the role of sender and receiver. Used with Swing.

(1)Server.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.*;

public class Server
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Server");
        JTextArea text = new JTextArea();

        frame.add(text);
        frame.setSize(600.300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        try
        {
            byte [] message = new byte[2048];
            DatagramSocket socket = new DatagramSocket(12345);
            DatagramPacket packet = new DatagramPacket(message, message.length);
            socket.receive(packet);

            InetAddress ip = packet.getAddress();
            int port = packet.getPort();
            text.setText("ip : "+ip.toString()+"\n");
            text.append("port : "+port+"\n");
            text.append("message : "+new String(packet.getData()));

            String messageFromServer = "Message from server";
            packet = new DatagramPacket(messageFromServer.getBytes(),messageFromServer.getBytes().length,ip,port);
            socket.send(packet);
            socket.close();
        }
        catch(IOException e) { e.printStackTrace(); }}}Copy the code

(2)Client.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.*;
import java.awt.GridLayout;
public class Client
{
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JTextArea text = new JTextArea();
        JButton send = new JButton("send");
        GridLayout layout = new GridLayout(2.1.1.1);

        frame.setLayout(layout);
        frame.setTitle("Client");
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setSize(600.300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(text);
        frame.add(send);
        send.addActionListener( v->
        {
            try
            {
                InetAddress ip = InetAddress.getByName("127.0.0.1");
                int port = 12345;
                DatagramSocket socket = new DatagramSocket(55555);
                String message = text.getText();
                DatagramPacket packet = new DatagramPacket(message.getBytes(),message.getBytes().length,ip,port);
                socket.send(packet);

                byte [] messageFromServer = new byte[2048];
                packet = new DatagramPacket(messageFromServer, messageFromServer.length);
                socket.receive(packet);
                text.setText(new String(packet.getData()));
                socket.close();
            }
            catch(IOException e) { e.printStackTrace(); }}); }}Copy the code

5. Test