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);
buf.clear();
//Wait for message to be received
channel.receive(buf);
//Data byte[]To receive
buf.flip();
byte[] data = new byte[buf.limit()];
buf.get(data);
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);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
//Send
int bytesSent = channel.send(buf, new InetSocketAddress("127.0.0.1", 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.
By the way, with Node.js, sending and receiving UDP is so easy.
Receive
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
server.bind(9999);
Send
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.send('Hello', 9999, '127.0.0.1', (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