Unity C#tcpclient流。阅读StartCoroutine问题

时间:2019-01-12 13:59:19

标签: c# multithreading unity3d tcpclient

我正在使用Unity3D开发TcpClient。

有问题。

                    if (length == Marshal.SizeOf(typeof(BATTLE_CHARACTER_DATA_GROUP_SEND))+1)
                    {

                            BATTLE_CHARACTER_DATA_GROUP_SEND bcdgs = new BATTLE_CHARACTER_DATA_GROUP_SEND();
                            bcdgs.Deserialize(ref bytes);
                            Debug.Log("bcdgs data Size : " + bcdgs.data_size);
                            StartCoroutine(PlayerObjectCreate(bcdgs));
                    }

如果您尝试在上面的代码中创建mainThread对象,但您运行StartCoroutine,它将向服务器端发送“ 0”客户端断开连接值。

我的代码怎么了?

下面是一些完整的来源。

        private void ConnectToTcpServer()
{
    try
    {
        clientReceiveThread = new Thread(new ThreadStart(ListenForData));
        clientReceiveThread.IsBackground = true;
        clientReceiveThread.Start();

    }
    catch (Exception e)
    {
        Debug.Log("On Client Connect Exception " + e);
    }
}
private void ListenForData()
{
    try
    {
        socketConnection = new TcpClient("192.168.235.128", 53390);
        if (socketConnection.Connected)
        {
            ServerConnected = true;
            Debug.Log("Connected!!!");
        }
        else
        {
            ServerConnected = false;
            Debug.Log("Not Connected!!!");
        }

        while (true)
        {

            using (NetworkStream stream = socketConnection.GetStream())
            {
                int length;
                byte[] bytes = new byte[Marshal.SizeOf(typeof(BATTLE_CHARACTER_DATA_GROUP_SEND))+1];
                while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                {                        
                    Debug.Log("length : " + length);
                    if (length == Marshal.SizeOf(typeof(BATTLE_CHARACTER_DATA_GROUP_SEND))+1)
                    {

                            BATTLE_CHARACTER_DATA_GROUP_SEND bcdgs = new BATTLE_CHARACTER_DATA_GROUP_SEND();
                            bcdgs.Deserialize(ref bytes);
                            Debug.Log("bcdgs data Size : " + bcdgs.data_size);

StartCoroutine(PlayerObjectCreate(bcdgs));
                    }
                }
            }
        }
    }
    catch (SocketException socketException)
    {
        Debug.Log("Socket Exception : " + socketException.ToString());            
    }
}

0 个答案:

没有答案