NetworkCursor

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
m (Description)
m (Expanded tabs - they fuck up rendering in Safari)
Line 9: Line 9:
 
==JavaScript - NetworkCursor.js==
 
==JavaScript - NetworkCursor.js==
 
<javascript>function Update () {
 
<javascript>function Update () {
while (true)
+
    while (true)
{
+
    {
var msg : MessageData = Server.PopMessage();
+
        var msg : MessageData = Server.PopMessage();
if (msg == null)
+
        if (msg == null)
break;
+
            break;
  
transform.position.x = msg.mousex;
+
        transform.position.x = msg.mousex;
transform.position.y = msg.mousey;
+
        transform.position.y = msg.mousey;
}
+
    }
 
}</javascript>
 
}</javascript>
  
Line 23: Line 23:
 
<javascript>function Update ()
 
<javascript>function Update ()
 
{
 
{
// Create the message it and send it off!
+
    // Create the message it and send it off!
var msgData = new MessageData();
+
    var msgData = new MessageData();
msgData.mousex = Input.mousePosition.x / Screen.width;
+
    msgData.mousex = Input.mousePosition.x / Screen.width;
msgData.mousey = Input.mousePosition.y / Screen.height;
+
    msgData.mousey = Input.mousePosition.y / Screen.height;
msgData.stringData = "Hello World";
+
    msgData.stringData = "Hello World";
+
   
Client.Send(msgData);
+
    Client.Send(msgData);
 
}</javascript>
 
}</javascript>
  
Line 39: Line 39:
  
 
public class Client : MonoBehaviour {
 
public class Client : MonoBehaviour {
+
   
public string m_IPAdress = "127.0.0.1";
+
    public string m_IPAdress = "127.0.0.1";
public const int kPort = 10253;
+
    public const int kPort = 10253;
  
private static Client singleton;
+
    private static Client singleton;
  
+
   
private Socket m_Socket;
+
    private Socket m_Socket;
void Awake ()
+
    void Awake ()
{
+
    {
m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+
        m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  
// System.Net.PHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
+
        // System.Net.PHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
// System.Net.IPAddress remoteIPAddress = ipHostInfo.AddressList[0];
+
        // System.Net.IPAddress remoteIPAddress = ipHostInfo.AddressList[0];
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(m_IPAdress);
+
        System.Net.IPAddress   remoteIPAddress  = System.Net.IPAddress.Parse(m_IPAdress);
+
       
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, kPort);
+
        System.Net.IPEndPoint   remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, kPort);
  
singleton = this;
+
        singleton = this;
m_Socket.Connect(remoteEndPoint);
+
        m_Socket.Connect(remoteEndPoint);
}
+
    }
+
   
void OnApplicationQuit ()
+
    void OnApplicationQuit ()
{
+
    {
m_Socket.Close();
+
        m_Socket.Close();
m_Socket = null;
+
        m_Socket = null;
}
+
    }
+
   
static public void Send(MessageData msgData)
+
    static public void Send(MessageData msgData)
{
+
    {
if (singleton.m_Socket == null)
+
        if (singleton.m_Socket == null)
return;
+
            return;
+
           
byte[] sendData = MessageData.ToByteArray(msgData);
+
        byte[] sendData = MessageData.ToByteArray(msgData);
byte[] prefix = new byte[1];
+
        byte[] prefix = new byte[1];
prefix[0] = (byte)sendData.Length;
+
        prefix[0] = (byte)sendData.Length;
singleton.m_Socket.Send(prefix);
+
        singleton.m_Socket.Send(prefix);
singleton.m_Socket.Send(sendData);
+
        singleton.m_Socket.Send(sendData);
}
+
    }
 
}</csharp>
 
}</csharp>
  
Line 89: Line 89:
 
public class Server : MonoBehaviour {
 
public class Server : MonoBehaviour {
  
static Server singleton;
+
    static Server singleton;
+
   
private Socket m_Socket;
+
    private Socket m_Socket;
+
   
ArrayList m_Connections = new ArrayList ();
+
    ArrayList m_Connections = new ArrayList ();
+
   
ArrayList m_Buffer = new ArrayList ();
+
    ArrayList m_Buffer = new ArrayList ();
ArrayList m_ByteBuffer = new ArrayList ();
+
    ArrayList m_ByteBuffer = new ArrayList ();
+
   
void Awake ()
+
    void Awake ()
{
+
    {
m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+
        m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);    
IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any , Client.kPort);
+
        IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any , Client.kPort);
  
m_Socket.Bind( ipLocal );
+
        m_Socket.Bind( ipLocal );
+
   
//start listening...
+
        //start listening...
m_Socket.Listen (100);
+
        m_Socket.Listen (100);
singleton = this;
+
        singleton = this;
}
+
    }
+
   
void OnApplicationQuit ()
+
    void OnApplicationQuit ()
{
+
    {
Cleanup();
+
        Cleanup();
}
+
    }
+
   
void Cleanup ()
+
    void Cleanup ()
{
+
    {
if (m_Socket != null)
+
        if (m_Socket != null)
m_Socket.Close();
+
            m_Socket.Close();
m_Socket = null;
+
        m_Socket = null;
+
   
foreach (Socket con in m_Connections)
+
        foreach (Socket con in m_Connections)
con.Close();
+
            con.Close();
m_Connections.Clear();
+
        m_Connections.Clear();
}
+
    }  
~Server ()
+
    ~Server ()
{
+
    {
Cleanup();
+
        Cleanup();    
}
+
    }
+
   
void Update ()
+
    void Update ()
{
+
    {
// Accept any incoming connections!
+
        // Accept any incoming connections!
ArrayList listenList = new ArrayList();
+
        ArrayList listenList = new ArrayList();
listenList.Add(m_Socket);
+
        listenList.Add(m_Socket);
Socket.Select(listenList, null, null, 1000);
+
        Socket.Select(listenList, null, null, 1000);
for( int i = 0; i < listenList.Count; i++ )
+
        for( int i = 0; i < listenList.Count; i++ )
{
+
        {
Socket newSocket = ((Socket)listenList[i]).Accept();
+
            Socket newSocket = ((Socket)listenList[i]).Accept();
m_Connections.Add(newSocket);
+
            m_Connections.Add(newSocket);
m_ByteBuffer.Add(new ArrayList());
+
            m_ByteBuffer.Add(new ArrayList());
Debug.Log("Did connect");
+
            Debug.Log("Did connect");
}
+
        }
+
       
// Read data from the connections!
+
        // Read data from the connections!
if (m_Connections.Count != 0)
+
        if (m_Connections.Count != 0)
{
+
        {
ArrayList connections = new ArrayList (m_Connections);
+
            ArrayList connections = new ArrayList (m_Connections);
Socket.Select(connections, null, null, 1000);
+
            Socket.Select(connections, null, null, 1000);
// Go through all sockets that have data incoming!
+
            // Go through all sockets that have data incoming!
foreach (Socket socket in connections)
+
            foreach (Socket socket in connections)
{
+
            {
byte[] receivedbytes = new byte[512];
+
                byte[] receivedbytes = new byte[512];
+
               
ArrayList buffer = (ArrayList)m_ByteBuffer[m_Connections.IndexOf(socket)];
+
                ArrayList buffer = (ArrayList)m_ByteBuffer[m_Connections.IndexOf(socket)];
int read = socket.Receive(receivedbytes);
+
                int read = socket.Receive(receivedbytes);
for (int i=0;i<read;i++)
+
                for (int i=0;i<read;i++)
buffer.Add(receivedbytes[i]);
+
                    buffer.Add(receivedbytes[i]);
+
               
while (true && buffer.Count > 0)
+
                while (true && buffer.Count > 0)
{
+
                {
int length = (byte)buffer[0];
+
                    int length = (byte)buffer[0];
+
                   
if (length < buffer.Count)
+
                    if (length < buffer.Count)
{
+
                    {
ArrayList thismsgBytes = new ArrayList(buffer);
+
                        ArrayList thismsgBytes = new ArrayList(buffer);
thismsgBytes.RemoveRange(length + 1, thismsgBytes.Count - (length + 1));
+
                        thismsgBytes.RemoveRange(length + 1, thismsgBytes.Count - (length + 1));
thismsgBytes.RemoveRange(0, 1);
+
                        thismsgBytes.RemoveRange(0, 1);
if (thismsgBytes.Count != length)
+
                        if (thismsgBytes.Count != length)
Debug.Log("Bug");
+
                            Debug.Log("Bug");
+
                       
buffer.RemoveRange(0, length + 1);
+
                        buffer.RemoveRange(0, length + 1);
byte[] readbytes = (byte[])thismsgBytes.ToArray(typeof(byte));
+
                        byte[] readbytes = (byte[])thismsgBytes.ToArray(typeof(byte));
  
MessageData readMsg = MessageData.FromByteArray(readbytes);
+
                        MessageData readMsg = MessageData.FromByteArray(readbytes);
m_Buffer.Add(readMsg);
+
                        m_Buffer.Add(readMsg);
+
                       
//Debug.Log(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
+
                        //Debug.Log(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
+
                       
if (singleton != this)
+
                        if (singleton != this)
Debug.Log("Bug");
+
                            Debug.Log("Bug");  
}
+
                    }
else
+
                    else
break;
+
                        break;
}
+
                }
+
               
// string output = Encoding.UTF8.GetString(bytes);
+
                // string output = Encoding.UTF8.GetString(bytes);
}
+
            }          
}
+
        }
}
+
    }
+
   
static public MessageData PopMessage ()
+
    static public MessageData PopMessage ()
{
+
    {
if (singleton.m_Buffer.Count == 0)
+
        if (singleton.m_Buffer.Count == 0)
{
+
        {
return null;
+
            return null;
}
+
        }
else
+
        else
{
+
        {
MessageData readMsg = (MessageData)singleton.m_Buffer[0];
+
            MessageData readMsg = (MessageData)singleton.m_Buffer[0];
singleton.m_Buffer.RemoveAt(0);
+
            singleton.m_Buffer.RemoveAt(0);
// Debug.Log(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
+
            // Debug.Log(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
return readMsg;
+
            return readMsg;
}
+
        }
}
+
    }
 
}</csharp>
 
}</csharp>
  
Line 218: Line 218:
 
public class MessageData {
 
public class MessageData {
  
public string stringData = "";
+
    public string stringData = "";
public float  mousex = 0;
+
    public float  mousex = 0;
public float  mousey = 0;
+
    public float  mousey = 0;
public int    type = 0;
+
    public int    type = 0;
+
   
public static MessageData FromByteArray(byte[] input)
+
    public static MessageData FromByteArray(byte[] input)
{
+
    {
// Create a memory stream, and serialize.
+
        // Create a memory stream, and serialize.
MemoryStream stream = new MemoryStream(input);
+
        MemoryStream stream = new MemoryStream(input);
// Create a binary formatter.
+
        // Create a binary formatter.
BinaryFormatter formatter = new BinaryFormatter();
+
        BinaryFormatter formatter = new BinaryFormatter();
+
   
MessageData data = new MessageData();
+
        MessageData data = new MessageData();
data.stringData = (string)formatter.Deserialize(stream);
+
        data.stringData = (string)formatter.Deserialize(stream);
data.mousex = (float)formatter.Deserialize(stream);
+
        data.mousex = (float)formatter.Deserialize(stream);
data.mousey = (float)formatter.Deserialize(stream);
+
        data.mousey = (float)formatter.Deserialize(stream);
data.type = (int)formatter.Deserialize(stream);
+
        data.type = (int)formatter.Deserialize(stream);
+
   
return data;
+
        return data;
}
+
    }
  
public static byte[] ToByteArray (MessageData msg)
+
    public static byte[] ToByteArray (MessageData msg)
{
+
    {
// Create a memory stream, and serialize.
+
        // Create a memory stream, and serialize.
MemoryStream stream = new MemoryStream();
+
        MemoryStream stream = new MemoryStream();
// Create a binary formatter.
+
        // Create a binary formatter.
BinaryFormatter formatter = new BinaryFormatter();
+
        BinaryFormatter formatter = new BinaryFormatter();
+
   
// Serialize.
+
        // Serialize.
formatter.Serialize(stream, msg.stringData);
+
        formatter.Serialize(stream, msg.stringData);
formatter.Serialize(stream, msg.mousex);
+
        formatter.Serialize(stream, msg.mousex);
formatter.Serialize(stream, msg.mousey);
+
        formatter.Serialize(stream, msg.mousey);
formatter.Serialize(stream, msg.type);
+
        formatter.Serialize(stream, msg.type);
+
       
// Now return the array.
+
        // Now return the array.
return stream.ToArray();
+
        return stream.ToArray();
}
+
    }
 
}</csharp>
 
}</csharp>

Revision as of 22:34, 11 July 2006

Author: (Joachim Ante)

Contents

Description

A set of scripts to make one Unity instance control another. This example takes mouse input one one Unity instance and sends it to control a cursor on another. This code could be developed further into a good networking implementation for many types of games.

Usage

Download this project: Networking Example Project

JavaScript - NetworkCursor.js

<javascript>function Update () {

   while (true)
   {
       var msg : MessageData = Server.PopMessage();
       if (msg == null)
           break;
       transform.position.x = msg.mousex;
       transform.position.y = msg.mousey;
   }

}</javascript>

JavaScript - SendNetworkCursor.js

<javascript>function Update () {

   // Create the message it and send it off!
   var msgData = new MessageData();
   msgData.mousex = Input.mousePosition.x / Screen.width;
   msgData.mousey = Input.mousePosition.y / Screen.height;
   msgData.stringData = "Hello World";
   
   Client.Send(msgData);

}</javascript>

C# - Plugins/Client.cs

<csharp>using UnityEngine; using System.Collections; using System.Net.Sockets; using System.Net;

public class Client : MonoBehaviour {

   public string m_IPAdress = "127.0.0.1";
   public const int kPort = 10253;
   private static Client singleton;


   private Socket m_Socket;
   void Awake ()
   {
       m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       // System.Net.PHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
       // System.Net.IPAddress remoteIPAddress = ipHostInfo.AddressList[0];
       System.Net.IPAddress    remoteIPAddress  = System.Net.IPAddress.Parse(m_IPAdress);
       
       System.Net.IPEndPoint   remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, kPort);
       singleton = this;
       m_Socket.Connect(remoteEndPoint);
   }
   
   void OnApplicationQuit ()
   {
       m_Socket.Close();
       m_Socket = null;
   }
   
   static public void Send(MessageData msgData)
   {
       if (singleton.m_Socket == null)
           return;
           
       byte[] sendData = MessageData.ToByteArray(msgData);
       byte[] prefix = new byte[1];
       prefix[0] = (byte)sendData.Length;
       singleton.m_Socket.Send(prefix);
       singleton.m_Socket.Send(sendData);
   }

}</csharp>

C# - Plugins/Server.cs

<csharp>using UnityEngine; using System.Collections; using System.Net.Sockets; using System.Net; using System.Text;

public class Server : MonoBehaviour {

   static Server singleton;
   
   private Socket m_Socket;
   
   ArrayList m_Connections = new ArrayList ();
   
   ArrayList m_Buffer = new ArrayList ();
   ArrayList m_ByteBuffer = new ArrayList ();
   
   void Awake ()
   {
       m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     
       IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any , Client.kPort);
       m_Socket.Bind( ipLocal );
   
       //start listening...
       m_Socket.Listen (100);
       singleton = this;
   }
   
   void OnApplicationQuit ()
   {
       Cleanup();
   }
   
   void Cleanup ()
   {
       if (m_Socket != null)
           m_Socket.Close();
       m_Socket = null;
   
       foreach (Socket con in m_Connections)
           con.Close();
       m_Connections.Clear();
   }   
   ~Server ()
   {
       Cleanup();      
   }
   
   void Update ()
   {
       // Accept any incoming connections!
       ArrayList listenList = new ArrayList();
       listenList.Add(m_Socket);
       Socket.Select(listenList, null, null, 1000);
       for( int i = 0; i < listenList.Count; i++ )
       {
           Socket newSocket = ((Socket)listenList[i]).Accept();
           m_Connections.Add(newSocket);
           m_ByteBuffer.Add(new ArrayList());
           Debug.Log("Did connect");
       }
       
       // Read data from the connections!
       if (m_Connections.Count != 0)
       {
           ArrayList connections = new ArrayList (m_Connections);
           Socket.Select(connections, null, null, 1000);
           // Go through all sockets that have data incoming!
           foreach (Socket socket in connections)
           {
               byte[] receivedbytes = new byte[512];
               
               ArrayList buffer = (ArrayList)m_ByteBuffer[m_Connections.IndexOf(socket)];
               int read = socket.Receive(receivedbytes);
               for (int i=0;i<read;i++)
                   buffer.Add(receivedbytes[i]);
               
               while (true && buffer.Count > 0)
               {
                   int length = (byte)buffer[0];
                   
                   if (length < buffer.Count)
                   {
                       ArrayList thismsgBytes = new ArrayList(buffer);
                       thismsgBytes.RemoveRange(length + 1, thismsgBytes.Count - (length + 1));
                       thismsgBytes.RemoveRange(0, 1);
                       if (thismsgBytes.Count != length)
                           Debug.Log("Bug");
                       
                       buffer.RemoveRange(0, length + 1);
                       byte[] readbytes = (byte[])thismsgBytes.ToArray(typeof(byte));
                       MessageData readMsg = MessageData.FromByteArray(readbytes);
                       m_Buffer.Add(readMsg);
                       
                       //Debug.Log(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
                       
                       if (singleton != this)
                           Debug.Log("Bug");   
                   }
                   else
                       break;
               }
               
               // string output = Encoding.UTF8.GetString(bytes);
           }           
       }
   }
   
   static public MessageData PopMessage ()
   {
       if (singleton.m_Buffer.Count == 0)
       {
           return null;
       }
       else
       {
           MessageData readMsg = (MessageData)singleton.m_Buffer[0];
           singleton.m_Buffer.RemoveAt(0);
           // Debug.Log(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
           return readMsg;
       }
   }

}</csharp>


C# - Plugins/MessageData.cs

<csharp>using UnityEngine; using System.Collections; using System.IO; using System.Runtime.Serialization.Formatters.Binary;

[System.Serializable] public class MessageData {

   public string stringData = "";
   public float  mousex = 0;
   public float  mousey = 0;
   public int    type = 0;
   
   public static MessageData FromByteArray(byte[] input)
   {
       // Create a memory stream, and serialize.
       MemoryStream stream = new MemoryStream(input);
       // Create a binary formatter.
       BinaryFormatter formatter = new BinaryFormatter();
   
       MessageData data = new MessageData();
       data.stringData = (string)formatter.Deserialize(stream);
       data.mousex = (float)formatter.Deserialize(stream);
       data.mousey = (float)formatter.Deserialize(stream);
       data.type = (int)formatter.Deserialize(stream);
   
       return data;
   }
   public static byte[] ToByteArray (MessageData msg)
   {
       // Create a memory stream, and serialize.
       MemoryStream stream = new MemoryStream();
       // Create a binary formatter.
       BinaryFormatter formatter = new BinaryFormatter();
   
       // Serialize.
       formatter.Serialize(stream, msg.stringData);
       formatter.Serialize(stream, msg.mousex);
       formatter.Serialize(stream, msg.mousey);
       formatter.Serialize(stream, msg.type);
       
       // Now return the array.
       return stream.ToArray();
   }

}</csharp>

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox