C#TCP Framing - 如何发送消息大小

时间:2017-12-07 10:25:56

标签: c# tcp

到目前为止,这是我的代码。

这是我的客户:

public void Send(string header, Dictionary<string, string> data)
{
    new Thread(() =>
    {
        Thread.CurrentThread.IsBackground = true;
        if (stream.CanRead)
        {
            socketReady = true;
        }

        if (!socketReady)
        {
            return;
        }
        JsonData SendData = new JsonData();
        SendData.header = "1x" + header;
        foreach (var item in data)
        {
            SendData.data.Add(item.Key.ToString(), item.Value.ToString());
        }
        SendData.connectionId = connectionId;

        string json = JsonConvert.SerializeObject(SendData);
        byte[] JsonToBytes = Encoding.ASCII.GetBytes(json);
        byte[] lengthArray = BitConverter.ToInt32(JsonToBytes, 0);
        stream.Write(lengthArray, 0, lengthArray.Length);
        stream.Write(JsonToBytes, 0, JsonToBytes.Length);
        stream.Flush();



        Debug.Log("Client World:" + json);
    }).Start();
}

这是我的服务器:

    private void Update()
    {
        //Console.WriteLine("Call");
        if (!serverStarted)
        {
            return;
        }

        foreach (ServerClient c in clients.ToList())
        {
            // Is the client still connected?
            if (!IsConnected(c.tcp))
            {
                c.tcp.Close();
                disconnectList.Add(c);
                Console.WriteLine(c.connectionId + " has disconnected.");
                CharacterLogout(c.connectionId);
                continue;
                //Console.WriteLine("Check for connection?\n");
            }
            else
            {                 
                // Check for message from Client.
                NetworkStream s = c.tcp.GetStream();
                if (s.DataAvailable)
                {
                    string data = c.streamReader.ReadLine();

                    if (data != null)
                    {
                        OnIncomingData(c, data);
                    }

                }
                //continue;
            }
        }

        for (int i = 0; i < disconnectList.Count - 1; i++)
        {
            clients.Remove(disconnectList[i]);
            disconnectList.RemoveAt(i);
        }


    }

请注意,Update()循环中会调用while

现在我没有TCP消息框架。我想将大小消息发送到服务器,然后服务器将其读取,直到达到该大小。

但是我不确定这个TCP框架是如何工作的。 我应该两次发送到服务器吗?首先是以字节为单位的实际大小和消息?

我知道我必须将此writer.WriteLine替换为writer.Write,然后在服务器端c.streamReader.ReadLine();替换为c.streamReader.Read();循环中插入的while 。我希望我的方式正确。

您可以编辑我的代码并添加注释并附上说明,以便了解此过程的工作原理吗?

0 个答案:

没有答案