I tried UDP communication with Java

I investigated how to do UDP communication with Java. I knew how to use DatagramSocket, but this time I investigated how to use java.nio.


First, let's write the code to receive, assuming that you know that a UDP message will be sent.

//Create UDP channel
DatagramChannel channel = DatagramChannel.open();

//Receive UDP messages destined for port 9999
channel.socket().bind(new InetSocketAddress(9999));

//Prepare a buffer to receive messages.
//If the message is larger than the buffer, the message that does not fit is discarded.
ByteBuffer buf = ByteBuffer.allocate(453);

//Wait for message to be received

//Data byte[]To receive
byte[] data = new byte[buf.limit()];


Next, let's write the code of the sender.

//Create UDP channel
DatagramChannel channel = DatagramChannel.open();
//Send UDP messages from port 9999
channel.socket().bind(new InetSocketAddress(9999));

//Make the data to be sent in the form of ByteBuffer.
//Here String->byte[]->Converted to ByteBuffer.
String newData = "New String to write to file..." + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesSent = channel.send(buf, new InetSocketAddress("", 41234));

It's the same whether you're receiving or sending, up to the point of creating a DatagramChannel and binding the socket. Then, convert the content you want to send and receive to ByteBuffer and exchange. I want to implement a low level protocol myself! If this is not the case, I think that it may be used for general purposes to convert the content of the message into a character string using a method such as JSON and send it as String->byte []-> ByteBuffer. .. For communication between Java applications, ObjectInputStream and ObjectOutputStream It is also possible to directly exchange arbitrary objects using (/io/ObjectOutputStream.html).

Please note that UDP does not guarantee that the message will reach the other party properly like TCP, so ** it will not cause an error even if it does not arrive. ** So it can be hard to find if you make a mistake in your code while debugging.

Extra edition

By the way, with Node.js, sending and receiving UDP is so easy.


const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.on('message', (msg, rinfo) => {
  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);

//Wait for reception on port 9999


const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.send('Hello', 9999, '', (err, bytes) => {
  console.log(err, bytes)

When debugging the UDP message sending / receiving part of a Java application, it may be convenient to write a test program in Node.js for temporary message sending.

Recommended Posts

I tried UDP communication with Java
I tried to interact with Java
I tried using OpenCV with Java + Tomcat
I tried to make Basic authentication with Java
I tried to break a block with java (1)
[Java] JSON communication with jackson
I tried DI with Ruby
I tried using Java REPL
I tried UPSERT with PostgreSQL.
I tried BIND with Docker
I tried metaprogramming in Java
[Java 11] I tried to execute Java without compiling with javac
I tried OCR processing a PDF file with Java
I tried to implement Stalin sort with Java Collector
I tried to create a java8 development environment with Chocolatey
I tried using JOOQ with Gradle
[K8s] I tried communication between pods!
I tried morphological analysis with MeCab
I tried the Java framework "Quarkus"
I tried using Java8 Stream API
What I learned with Java Gold
I tried using JWT in Java
I tried GraphQL with Spring Boot
Try bidirectional communication with gRPC Java
I tried to summarize Java learning (1)
I tried Flyway with Spring Boot
What I learned with Java Silver
I tried to summarize Java 8 now
I tried OCR processing a PDF file with Java part2
I tried customizing slim with Scaffold
I tried using the CameraX library with Android Java Fragment
I tried using Java memo LocalDate
I tried using GoogleHttpClient of Java
I tried to make an Android application with MVC now (Java)
I tried using Elasticsearch API in Java
I tried using Realm with Swift UI
I tried Cassandra's Object Mapper for Java
I tried to summarize Java lambda expressions
Java9 was included, so I tried jshell.
I tried to get started with WebAssembly
I tried using Scalar DL with Docker
I tried the new era in Java
Memo when HTTP communication with Java (OkHttp)
I tried using OnlineConverter with SpringBoot + JODConverter
I tried time-saving management learning with Studyplus.
I tried playing with BottomNavigationView a little ①
I tried Lazy Initialization with Spring Boot 2.2.0
I tried Google's entrance exam (unofficial) [java]
I tried to implement ModanShogi with Kinx
I tried Spring.
I tried tomcat
I tried youtubeDataApi.
I tried refactoring ①
I tried FizzBuzz.
I tried JHipster 5.1
I tried putting Java on my Mac easily
I tried to verify AdoptOpenJDK 11 (11.0.2) with Docker image
I tried to manage struts configuration with Coggle
I tried to manage login information with JMX
java I tried to break a simple block
I tried writing CRUD with Rails + Vue + devise_token_auth