UDP (Unity & Node JS)
In this tutorial, I will create UDP Server & UDP Client , the server will be NodeJS Server and the UDP Client will be C# on Unity3d.
About UDP
UDP stands for User Datagram Protocol
UDP is a stateless connection and unreliable, however it can be efficient and it’s much faster than TCP connections.
For more information about the difference between UDP & TCP, check this link here.
NodeJS UDP Server
Create a default package.json
npm init -y
Import dgram module from npm
npm i dgram
Create index.js which will be our UDP server
touch index.js
Next the server code
const dgram = require('dgram');const server = dgram.createSocket('udp4');server.on('error', (err) => {console.log(`server error:\n${err.stack}`);server.close();});server.on('message', (msg, senderInfo) => {console.log('Messages received '+ msg)server.send(msg,senderInfo.port,senderInfo.address,()=>{console.log(`Message sent to ${senderInfo.address}:${senderInfo.port}`)
})});server.on('listening', () => {const address = server.address();console.log(`server listening on ${address.address}:${address.port}`);});server.bind(5500);
First we import the nodeJS dgram module which is an implementation of UDP datagram sockets.
Next, we create a UDP socket which will be udp4 for IPV4.
dgram module have some events that we can listen to and trigger our callbacks.
“error”, “message”, “listening”, are some of the events we are listening to.
on “error”, we print the error and close the server.
on “listening”, we print our server address.
on “message”, we just forward the message back to the client.
Unity UDP Client
I will be using C# UDP Client in System.Net.Sockets
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;public class UDP_Client : MonoBehaviour
{
void Start()
{
UDPTest();
}void UDPTest()
{
UdpClient client = new UdpClient(5600);
try
{
client.Connect("127.0.0.1", 5500);
byte[] sendBytes = Encoding.ASCII.GetBytes("Hello, from the client");
client.Send(sendBytes, sendBytes.Length);IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 5500);byte[] receiveBytes = client.Receive(ref remoteEndPoint);
string receivedString = Encoding.ASCII.GetString(receiveBytes);print("Message received from the server \n " + receivedString);
}
catch(Exception e)
{
print("Exception thrown " + e.Message);
}
}
}
First I added the needed namespaces
System.Net & System.Net.Sockets are for UDP Client and
System.Text are for Encoding and Decoding the text (Converting the string to byte array and vice versa)
System for the Exception
UnityEngine for adding Monobehaviour
Next, I created a function called UDPTest where we will do the following:
- Create a UDP Client and assign a receive port to it (5600).
- Create a try catch block for the UDP Connection, In the case of an Exception thrown, just print the exception message
- Define the remote connection, in client.Connect and remoteEndPoint.
- Send a message “Hello, From the client” (We send byte array not the actual text)
- receive the message and convert the byte array back to text.