UDP simple server client code example

UDP simple server client code example

I won’t go into details about the theory of UDP. I will just give you a HelloWorld program about UDP. The code is clear and I hope it will be helpful to the beginners!

Of course, actually, I am just getting started in this area!

First, write the server code. The server binds the local IP and port to listen for access:

package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * UDP service class */
public class UdpServerSocket {
	
	private byte[] buffer = new byte[1024];
	private static DatagramSocket ds = null;
	private DatagramPacket packet = null;
	private InetSocketAddress socketAddress = null;
	
	/**
	 * Test method */
	public static void main(String[] args) throws Exception {
		String serverHost = "127.0.0.1";
		int serverPort = 3344;
		UdpServerSocket udpServerSocket = new UdpServerSocket(serverHost,
				serverPort);
		while (true) {
			udpServerSocket.receive();
			udpServerSocket.response("Hello, have you eaten?");
		}		
	}

	/**
	 * Constructor, bind host and port */
	public UdpServerSocket(String host, int port) throws Exception {
		socketAddress = new InetSocketAddress(host, port);
		ds = new DatagramSocket(socketAddress);
		System.out.println("Server started!");
	}

	/**
	 * Receive data packets. This method will cause thread blocking */
	public final String receive() throws IOException {
		packet = new DatagramPacket(buffer, buffer.length);
		ds.receive(packet);
		String info = new String(packet.getData(), 0, packet.getLength());
		System.out.println("Receive information: " + info);
		return info;
	}

	/**
	 * Send the response packet to the requester */
	public final void response(String info) throws IOException {
		System.out.println("Client address: " + packet.getAddress().getHostAddress()
				+ ",port:" + packet.getPort());
		DatagramPacket dp = new DatagramPacket(buffer, buffer.length, packet
				.getAddress(), packet.getPort());
		dp.setData(info.getBytes());
		ds.send(dp);
	}
}

After running, it prompts that the server runs successfully, the program starts to listen to the port, the receiving method is blocked, and it will proceed only when there is access!

When we write a client to access it, we see that the examples on the Internet all directly create a DatagramSocket object, but in fact we don’t know which port we are using. Here I will specify the port I bind to when I create it. In fact, it is very simple. Just pass a port parameter when initializing the object.

Here when you access the client, the client will print your IP and port!

Take a look at the client code:

package udp;

import java.io.*;
import java.net.*;

/**
 * UDP client program, used to send data to the server and receive the server's response information*/
public class UdpClientSocket {
	private byte[] buffer = new byte[1024];

	private static DatagramSocket ds = null;
	
	/**
	 * Test the client's method of sending packets and receiving response information */
	public static void main(String[] args) throws Exception {
		UdpClientSocket client = new UdpClientSocket();
		String serverHost = "127.0.0.1";
		int serverPort = 3344;
		client.send(serverHost, serverPort, ("Hello, dear!").getBytes());
		byte[] bt = client.receive();
		System.out.println("Server response data: " + new String(bt));
		// Close the connection try {
			ds.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Constructor, create UDP client */
	public UdpClientSocket() throws Exception {
		ds = new DatagramSocket(8899); // Bind to local port as client }
	
	/**
	 * Send data information to the specified server */
	public final void send(final String host, final int port,
			final byte[] bytes) throws IOException {
		DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(host), port);
		ds.send(dp);
	}

	/**
	 * Receive data sent back from the specified server */
	public final byte[] receive()
			throws Exception {
		DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
		ds.receive(dp);		
		byte[] data = new byte[dp.getLength()];
		System.arraycopy(dp.getData(), 0, data, 0, dp.getLength());		
		return data;
	}
}

Run the program directly to see the effect!

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Detailed explanation of Python UDP programming
  • C# Sample code using TCP/UDP protocol
  • Java network based on UDP chat program example analysis
  • Java simulated UDP communication sample code
  • Python implements UDP program communication process diagram
  • Python implements file transfer under UDP protocol
  • Java UDP communication client and server example analysis
  • UDP connection object principle analysis and usage examples

<<:  Mysql example of converting birth date into age and grouping and counting the number of people

>>:  A brief analysis of MySQL parallel replication

Recommend

MySql index detailed introduction and correct use method

MySql index detailed introduction and correct use...

Implementation of breakpoint resume in Node.js

Preface Normal business needs: upload pictures, E...

Implementation and usage scenarios of JS anti-shake throttling function

Table of contents 1. What is Function Anti-shake?...

Solution to the impact of empty paths on page performance

A few days ago, I saw a post shared by Yu Bo on G...

Installation tutorial of MySQL 5.1 and 5.7 under Linux

The operating system for the following content is...

Docker builds kubectl image implementation steps

If the program service is deployed using k8s inte...

About CSS floating and canceling floating

Definition of Float Sets the element out of the n...

Sample code for testing technology application based on Docker+Selenium Grid

Introduction to Selenium Grid Although some new f...

How to insert 10 million records into a MySQL database table in 88 seconds

The database I use is MySQL database version 5.7 ...

Detailed explanation of asynchronous programming knowledge points in nodejs

Introduction Because JavaScript is single-threade...

Detailed explanation of the principle and function of JavaScript closure

Table of contents Introduction Uses of closures C...

Explore the truth behind the reload process in Nginx

Today's article mainly introduces the reload ...