Unity & NodeJS
Published in

Unity & NodeJS

UDP Client & Server using NodeJS and Unity3d

UDP (Unity & Node JS)

UDP Unity C# & NodeJS Server

About UDP

NodeJS UDP Server

npm init -y
npm i dgram
touch index.js
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);

Unity UDP Client

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);
}
}
}
  1. Create a UDP Client and assign a receive port to it (5600).
  2. Create a try catch block for the UDP Connection, In the case of an Exception thrown, just print the exception message
  3. Define the remote connection, in client.Connect and remoteEndPoint.
  4. Send a message “Hello, From the client” (We send byte array not the actual text)
  5. receive the message and convert the byte array back to text.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store