New to Unity - Need help with networking

I’m fairly new to Unity and I have been getting my hands dirty trying to learn how to do some ‘basic’ networking. I’ve been trying to get a simple server / multiple client setup working using RPC and I seem to be missing something.

What I would like to do is have a simple dedicated server running - using the RAKNET library (which I know Unity uses) and then have a number of Unity clients connect to this and use RPC to send messages to the server and for the server to send back responses.

I don’t need any master server functionality as there will only be one server that all clients connect to.

Can someone point me in the right direction either via documentation or examples?

Thanks in advance…

Personally, I’d set up the server with Unity, as I would guess that in most cases, you’ll have rather significant game logic residing on the server, and the way Unity is handling networking (making extensive Use of NetworkViews) might be tricky to set up only using RAKNET (I don’t know that API as “standalone”, so I don’t know how much of what Unity is using is part of that API).

I could think of a few other good reasons creating your server with Unity, like very nice testing features, sharing code between client and server etc. etc. etc.

The major disadvantage of that approach is that Unity doesn’t support a headless mode, yet - at least not for Unix or Windows (which I think is a much more convenient server OS than Mac OS… simply because it’s available, and comparatively cheap to get dedicated servers with these OSs). I hope that when more people are developing multplayer games, the issues involved in setting up (distributed, hosted) standalone servers will be handled… This has been brought up before, so I won’t repeat it…

The solution is to simply switch off the cameras and live with the inconveniences of having an application where you would actually want to have a service (speaking “Windows speak”). Or having to rent a Windows server, where you might prefer renting a Linux box :wink:

If you can live with that, check out the examples and the documentation - it’s really rather well-documented (except for a few things that haven’t been updated, yet - you can now use bool and byte[ ] as parameters for RPCs). The server would then simply be a “different build” of your game project, and based on, for instance, a variable globally accessible through a singleton pattern, you could check the relevant code paths.

Btw, I’m using the master server functionality even though I’m also only having one single standalone server that clients connect to. Reason is simple: It seemed to me that this is the easiest and most painless way of setting things up (including NAT punchthrough and stuff like that).

Um… links… see my other posting in thread;

http://forum.unity3d.com/viewtopic.php?t=9478 (almost at the end, I had a little collection of nice links into the documentation)

If you really want to build your server based on RAKNET (without Unity wrapping around it), I guess Larus is the only one who can help you :wink:

Jashan

Thanks Jashan for the information you provided. Perhaps I should explain in a little more detail what I am trying to achieve.

I have been working on a MUD Server, which is written in C++ and works well, but is currently limited to telnet access. This tends not to give way to a good user interface and does look kind of dated.

I would like to use Unity as a ‘front end’ to the server to provide a better, more graphical front end to the server. At first I would just like to have a simple interface, which would simulate what I have already. I would then like to take this further by adding buttons for directions, inventory etc.

I feel this would be a better approach to learning the ins and outs of an MMO, rather than jumping in the deep end as I have seen so many attempt and fail.

Which I guess would mean that I fall into the option of adding RAKNET to my existing server to allow me to integrate with Unity.

I still have not managed to get a stand alone server talking to Unity using RPC, so if anyone else has any information it would be greatly received.

Hi… um… Jason, maybe? :wink:

thanks for the clarification… well, from that perspective, it obviously would make a lot of sense to add RAKNET to your MUD-server to get it to talk to Unity. I’m not sure though, how this can be done… Guess it depends largely on the documentation of the “internals” of how Unity networking is implemented on top of RAKNET… I guess Larus might probably tune in to this thread - he’s the guy (or at least: one of the guys :wink: ) who’s been creating the networking part of Unity.

If you don’t want to wait for that, you might also try sniffing the packets from some RAKNET demo (that you might have to create for this) and sniffing the packets from one of the Unity networking demos - maybe you can decode the protocol(s) involved and create your RAKNET layer that way. You might also want to check out the Master server. As far as I know, it’s sources are open - and you can probably gain a lot of valuable insights from there, relevant also to what you’re trying to do…

For the MMO-stuff, having some low-level experience sure wouldn’t hurt, anyways :wink:

Sunny regards,
Jashan

The message protocol is not documented. Making a separate server using RakNet will be non-trivial to do at the moment, its not directly supported. You could just do your server part in Unity, like Jashan has suggested, maybe in a minimalist way. Then of course you can only run it on Mac and Windows, not Linux.

If you already have a working server running you could implement the client part using .NET sockets within Unity.

I’ve found the example below which I think could be made to do what I want. Obviously, I would have to make some changes on my MUD server side to work with this but I think it is certainly possible.

http://www.unifycommunity.com/wiki/index.php?title=Simple_TCP/IP_Client_-_Server

Now my question is, how do I get this into Unity and do I need the Pro version to get this working? What I want to do is simply hook it up to the GUI and at first will just have 2 text boxes, 1 for input (a single 80 character line will do for this) and a larger one for the out put from the server, again 80 characters wide but maybe around 20 lines (with side scrolling to go back up).

I have managed to get it so that if I press a key it sends text to the server. For a simple test I set up the u and p key to simply send the username and password of a character on the MUD, but the integration with the GUI is causing me some frustration at the moment.

Any help would be appreciated! If I need to buy Pro I don’t mind, if that is the only way forward, but I thought I would ask before I get my wallet out.

After a little more playing around I have come up with the following:

using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.IO;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
using SharpConnect;

public class LinkSyncSCR : MonoBehaviour {
	public Connector test=new Connector();
	string lastMessage;
	string myText;

	public Transform PlayerCoord;
	
	void Start () 
	{
		myText = "";
		
		Debug.Log(test.fnConnectResult("192.168.200.121",8888));
		
		if (test.res !="")
		{
			Debug.Log(test.res);
		}
		
	}
	
	void Update () 
	{
	}
   
	void OnGUI ()
	{
		GUI.Label (new Rect(5,5,450,250), test.strMessage);
		
		myText = GUI.TextField (new Rect(5, 250, 200, 20), myText);
		
		if (GUI.Button(new Rect(210, 250, 45, 20), "Send"))
		{ 
      		test.fnPacketTest(myText); 
      		myText = ""; 
		} 
	}
	
	void OnApplicationQuit ()
	{
		try
		{
			test.fnDisconnect();
		}
		catch
		{
		}
	}
}


namespace SharpConnect
{
	public class Connector 
	{
		const int READ_BUFFER_SIZE = 1024;
		const int PORT_NUM = 10000;
		private TcpClient client;
		private byte[] readBuffer = new byte[READ_BUFFER_SIZE];
		public ArrayList lstUsers=new ArrayList();
		public string strMessage=string.Empty;
		public string res=String.Empty;
 
		public Connector(){}
 
		public string fnConnectResult(string sNetIP, int iPORT_NUM)
		{
			try 
			{
				// The TcpClient is a subclass of Socket, providing higher level 
				// functionality like streaming.
				client = new TcpClient(sNetIP, iPORT_NUM);
				// Start an asynchronous read invoking DoRead to avoid lagging the user
				// interface.
				client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
				// Make sure the window is showing before popping up connection dialog.
				
				return "Connection Succeeded";
			} 
			catch(Exception ex)
			{
				return "Server is not active.  Please start server and try again." + ex;
			}
		}

		public void fnPacketTest(string sInfo)
		{
			SendData(sInfo);
		}
 
		public void fnDisconnect()
		{
			SendData("quit");
		}
 
		private void DoRead(IAsyncResult ar)
		{ 
			int BytesRead;
			try
			{
				// Finish asynchronous read into readBuffer and return number of bytes read.
				BytesRead = client.GetStream().EndRead(ar);
				
				if (BytesRead < 1) 
				{
					// if no bytes were read server has close.  
					res="Disconnected";
					return;
				}

				// Convert the byte array the message was saved into, minus two for the
				// Chr(13) and Chr(10)
				strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 2);

				// Start a new asynchronous read into readBuffer.
				client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
 
			} 
			catch
			{
				res="Disconnected";
			}
		}
 
		// Use a StreamWriter to send a message to server.
		private void SendData(string data)
		{
			StreamWriter writer = new StreamWriter(client.GetStream());
			writer.Write(data + (char) 13);
			writer.Flush();
		}
	}
}

This is very very crude, but it does kind of work! Probably not the best way of doing this, but at least it is a start.

Comments welcome…