Search code examples
androidnode.jsunity-game-enginewebsocketmmo

Creating a websocket for an android MMO using Unity3d and Node.js


I'm developing an android MMO android game in free version of Unity. I have node.js installed on my pc. should i use the following server-client side code because when i tried to test it i could get the server side script running but couldn't figure out whether the client is connecting or not. Also when i tried to build the apk, unity gives an error saying "using System.Net.Sockets requires pro version of unity." Please help!!

server side (on node.js)

`var net = require('net');
var tcp_server = net.createServer(function(socket)
{

    socket.write('hello\n');
    socket.end('world\n');
});
tcp_server.listen(8000);
console.log("Server Running...");`

client side (in unity c# script)

`using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Text;
public class tcpClient : MonoBehaviour 
{
    static void Main(string[] args)
    {
        Debug.Log("start");
        TcpClient tcpClient = new TcpClient();
        tcpClient.Connect("127.0.0.1", 8000);
        Debug.Log ("Connected");
        NetworkStream clientStream = tcpClient.GetStream();
        byte[] message = new byte[4096];
        int bytesRead;
        bytesRead = 0;

        try
        {
            // Read up to 4096 bytes
            bytesRead = clientStream.Read(message, 0, 4096);
        }
        catch
        {
            /*a socket error has occured*/
        }
        //We have read the message.
        ASCIIEncoding encoder = new ASCIIEncoding();
        Debug.Log(encoder.GetString(message, 0, bytesRead));
        //Console.WriteLine(encoder.GetString(message, 0, bytesRead));
        tcpClient.Close();
    }
}`

Solution

  • The easiest way would probably be to use socket.io

    http://socket.io/get-started/