Super simple UDP server example?

Could someone post a super simple UDP server example script, preferably in Javascript? I’m trying to pass data from my Unity application to an external Windows application. The data is simply a text string (about 30 characters) that I will send once per second. It’s been recommended that it would be easiest if I used UDP. I’m having a real hard time getting my head around this so a simple example would be tons of help. Thanks!

Bumpity - bump?

Hello Kahuna!

A server or a client are both quite easy to implement involving only a couple classes. They probably suggested UDP to you as it’s connectionless and makes sense for a local machine setup, the localhost loop is quite reliable, but tbqh a TCP setup isn’t that much more difficult.

If you search google for “C# UDP Server” you’ll find an ocean of examples that you can use in Unityscript or whatever language you’re writing your Windows standalone client in.

Hi Quietus! :slight_smile:

Your google skills are far better honed than mine, that looks like an excellent example, thanks!

Hi,
there is an example from a community member :

http://forum.unity3d.com/threads/15900-simple-udp-implementation-(send-read-via-mono-c-)?highlight=server

Maybe this will help you, too.


oxl

Thanks oxl, I tried that script but decided I needed something even simpler as I really don’t know anything about networking (and almost nothing about C#).

Ooops, you were looking for a JS example . Didn’t actually read this, sorry.


oxl

No worries oxl, any help is always appreciated. :wink:

The code there though requires only requires syntax updates and will then work on unityscript without any problem. (syntax update means using → import private void etc → function, type varname = var varName : type)

The problem with “simple” is that UDP then is the wrong path to take because UDP is pretty complex the moment you want to go further than you host it and setup your firewall due to the required NAT punchthrough and other issues and specifics you have to keep in mind.

Before going to this “0” level, I would consider looking at lidgren and only go with raw udp sockets if you need something that not even lidgren can fullfill for ya

The OP was looking for interprocess communications on a local machine. No firewalls, NAT translation, routers or interwebs involved.

Quietus is right. What I was looking for was a simple way to “broadcast” a short text string about once per second to another Windows application (both apps will reside on the same machine). The Windows app’s developer recommended I look at using UDP so that prompted my search.

args my error :frowning:
hands himself over the stupid being award

For this kind of usage UDP indeed might be the best approach.
Also at 1 message a second you do not even need threading.

So would the example Quietus linked work for what I want to do?

for the receiving side, definitely.

for sending I would use the simpleclient shown at the page quietus provided ( Simple Udp Client : Udp Client « Network « C# / C Sharp )

all you need to do is get rid of that while(true) loop, instead you want to use something basing on update or coroutine

Ok, I’ve started the C# to Js conversion of the script in the link, here’s what I have so far:

import System;
import System.Net;
import System.Net.Sockets;
import System.Text;

var recv : int;
var data : byte[] = new byte[1024];
var ipep : IPEndPoint = new IPEndPoint(IPAddress.Any, 9050);
var newsock : Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

function Main () {
	newsock.Bind(ipep);
	Debug.Log("Waiting for a client...");
	
	var sender : IPEndPoint = new IPEndPoint(IPAddress.Any, 0);
	var Remote : EndPoint = (EndPoint)(sender);
	//Remote = (EndPoint)(sender);

	recv = newsock.ReceiveFrom(data, Remote);
	
	Debug.Log("Message received from {0}:" + Remote.ToString());
	Debug.Log(Encoding.ASCII.GetString(data, 0, recv));
	
	var welcome : String = "Welcome to my test server";
	data = Encoding.ASCII.GetBytes(welcome);
	newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
}

function SendSocket () {
	data = new byte[1024];
	recv = newsock.ReceiveFrom(data, Remote);
	Debug.Log(Encoding.ASCII.GetString(data, 0, recv));
	newsock.SendTo(data, recv, SocketFlags.None, Remote);
}

I’m not sure that I’m going in the right direction on this though, could someone take a look and tell me if it’s looking OK? This script is still giving me an error that “Cannot create instance of abstract class ‘System.Net.EndPoint’”. Any suggestions? Any other errors you can see?

Ok, no love for that question so let me ask this instead: I’m trying the C# version of that sample script instead. I’ve edited it so it doesn’t give me any errors in the Unity editor, but it still doesn’t appear to be working (I should see the “Welcome” message on the client, right?). Any ideas?

using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SimpleUdpSrvr : MonoBehaviour {
	public static void Main() {
		int recv;
		byte[] data = new byte[1024];
		IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
	
		Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

		newsock.Bind(ipep);
		Debug.Log("Waiting for a client...");

		IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
		EndPoint Remote = (EndPoint)(sender);

		recv = newsock.ReceiveFrom(data, ref Remote);

		Debug.Log("Message received from {0}:" + Remote.ToString());
		Debug.Log(Encoding.ASCII.GetString(data, 0, recv));

		string welcome = "Welcome to my test server";
		data = Encoding.ASCII.GetBytes(welcome);
		newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
		while(true) {
			data = new byte[1024];
			recv = newsock.ReceiveFrom(data, ref Remote);
       
			Debug.Log(Encoding.ASCII.GetString(data, 0, recv));
			newsock.SendTo(data, recv, SocketFlags.None, Remote);
		}
	}
}

FWIW, the client is set to listen at 127.0.0.1 / 9050.

Given the client code works correctly and is running before the server runs (as the server sends it only once before it enters the loop) and given you parse the data you get back to string from its ASCII nature, you should see “welcome to my test sever” yes.

argh I can’t get this to work :face_with_spiral_eyes: One more try:

Here’s an even simpler Udp server example I found and converted for Unity:

using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UdpSrvrSample : MonoBehaviour {
	public static void Main() {
		byte[] data = new byte[1024];
		IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
		UdpClient newsock = new UdpClient(ipep);

		Debug.Log("Waiting for a client...");

		IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

		data = newsock.Receive(ref sender);

		Debug.Log("Message received from {0}:" + sender.ToString());
		Debug.Log(Encoding.ASCII.GetString(data, 0, data.Length));

		string welcome = "Welcome to my test server";
		data = Encoding.ASCII.GetBytes(welcome);
		newsock.Send(data, data.Length, sender);

		while(true)
		{
			data = newsock.Receive(ref sender);
       
			Debug.Log(Encoding.ASCII.GetString(data, 0, data.Length));
			newsock.Send(data, data.Length, sender);
		}
	}
}

Here’s my conversion (so far) to Unityscript:

import System;
import System.Net;
import System.Net.Sockets;
import System.Text;

function Main() {
	var udata : byte[] = new byte[1024];
	var ipep : IPEndPoint = new IPEndPoint(IPAddress.Any, 9050);
	var newsock : UdpClient = new UdpClient(ipep);

	Debug.Log("Waiting for a client...");

	var sender : IPEndPoint = new IPEndPoint(IPAddress.Any, 0);

	udata = newsock.Receive(sender);

	Debug.Log("Message received from {0}:" + sender.ToString());
	Debug.Log(Encoding.ASCII.GetString(udata, 0, udata.Length));

	var welcome : String = "Welcome to my test server";
	udata = Encoding.ASCII.GetBytes(welcome);
	newsock.Send(udata, udata.Length, sender);

	while(true) {
		udata = newsock.Receive(sender);
      
		Debug.Log(Encoding.ASCII.GetString(udata, 0, udata.Length));
		newsock.Send(udata, udata.Length, sender);
	}
}

My Unityscript (obviously) doesn’t work nor do I have any idea how to get it to work. Been pounding my head against this wall all morning. :stuck_out_tongue:

1 Like

The js one shows that you indeed have not replaced the while(true) with something that can work with unity.

right now you basically infinite lock the whole engine.

what you need to do is take the whole sending / receiving related part (I would make the first half feed class variables instead of in function ones) and move it into update or coroutine as mentioned far up.

The code you converted there was for standalone console C# applications which show what they do on a very basic level but they do it very badly when it comes to actual usage as they hook 100% cpu, they do not even have thread sleep for 1 ms in for example.

so a recommended example would be (written out of head)

import System;
import System.Net;
import System.Net.Sockets;
import System.Text;

var udata : byte[];
var newsock : UdpClient;
var sender : IPEndPoint;

function Start() {
	udata = new byte[1024];
	var ipep : IPEndPoint = new IPEndPoint(IPAddress.Any, 9050);
	newsock = new UdpClient(ipep);

	Debug.Log("Waiting for a client...");

	sender = new IPEndPoint(IPAddress.Any, 0);
}

function Update()
{
	udata = newsock.Receive(sender);

	Debug.Log("Message received from {0}:" + sender.ToString());
	Debug.Log(Encoding.ASCII.GetString(udata, 0, udata.Length));

	var welcome : String = "Welcome to my test server";
	udata = Encoding.ASCII.GetBytes(welcome);
	newsock.Send(udata, udata.Length, sender);

}

I assume the UdpSvr would be a real console .NET application that you run or part of another application thats native .net or alike, in which case I would have something continously call that, bind it to a timer that does or push it in an own thread where you use thread sleep for 1 ms

Thanks dreamora, PM sent…