TCP套接字消息传递Unity3d c#

时间:2013-08-17 13:01:50

标签: c# sockets tcp network-programming unity3d

我正在制作一个原型,用于接收和发送消息从服务器到客户端和反之亦然。我正在使用wiki script进行一些更改,这在某种程度上可以正常工作。即,只要客户端连接到服务器,我就可以看到传递给服务器的消息,并且也可以从服务器获得回复。但是当我尝试在运行时手动输入消息时,循环失败。它会冻结Unity,因为在手动发送自定义消息时,我会将侦听器计为0。

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

public class Server : MonoBehaviour 
{

public static Server singleton;
private Socket m_Socket;
private bool canSend=false;
ArrayList m_Connections = new ArrayList ();
ArrayList listenList = new ArrayList();
ArrayList m_Buffer = new ArrayList ();
ArrayList m_ByteBuffer = new ArrayList ();

MessageData m = new MessageData();
private Rect grp;
private Rect box;
private bool sendMsg=false;

void Awake ()
{
    singleton = this;
    m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     
    IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any , 10254);
    if(!m_Socket.IsBound)
        m_Socket.Bind(ipLocal);
    print("Server Created");
    //start listening...
    m_Socket.Listen(1000);

    grp = new Rect(Screen.width/3f,Screen.height/4f,Screen.width/2.5f,Screen.height/2.5f);
    box = new Rect(0f,0f,Screen.width/2.5f,Screen.height/2.4f);
    m.stringData="";

}

void OnApplicationQuit ()
{
    Cleanup();
}

void Cleanup ()
{
    print("called 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!
    if (m_Socket != null)
        print("null");
    listenList.Add(m_Socket);

    Socket.Select(listenList, null, null, 1000);
    // Count = 1 ===>
    print("111 listenList.Count "+listenList.Count+"  "+m_Socket.IsBound);

    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 ");

        //Send Response
        m.stringData="Welcome to the server";
        byte[] sendData = MessageData.ToByteArray(m);
        byte[] prefix = new byte[1];
        prefix[0] = (byte)sendData.Length;
        newSocket.Send(prefix);
        newSocket.Send(sendData);

        print("Respose sent to client");
    }
    print("== listenList.Count "+listenList.Count);
    // 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 = (int)(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);
                    print("Message : "+readMsg.stringData);
                    if (singleton != this)
                        Debug.Log("Bug");   
                }
                else
                    break;
            }  
        }           
    }
}

static public string 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}", readMsg.stringData));
        return readMsg.stringData;
    }
}

public void SendResponce (MessageData m)
{
    m_Socket.Listen(1000);
    listenList.Add(m_Socket);
    Socket.Select(listenList, null, null, 1000);

    //Count=0 Problem ===> 
    print("222 listenList.Count "+listenList.Count);
    for( int i = 0; i < listenList.Count; i++ )
    {
        Socket newSocket = ((Socket)listenList[i]).Accept();
        byte[] sendData = MessageData.ToByteArray(m);
        byte[] prefix = new byte[1];
        prefix[0] = (byte)sendData.Length;
        newSocket.Send(prefix);
        newSocket.Send(sendData);
        print("Data sent to Socket "+newSocket.AddressFamily);
    }
}

void OnGUI ()
{
    GUI.BeginGroup(grp);
    GUI.Box(box,"Send message");
    GUI.Label(new Rect(80f,50f,100f,25f),"Message");
    m.stringData = GUI.TextField(new Rect(180f,50f,100f,25f),m.stringData);
    if(GUI.Button(new Rect(100f,150f,70f,25f),"Send"))
    {
        SendResponce(m);
        m.stringData="";
    }
    GUI.EndGroup();
}
}

0 个答案:

没有答案