socket 收发同步问题 解决方法

socket 收发同步问题 解决方法
首先:服务端要发四个字节过来,代表接下来他发了多少数据过来,然后每次客户端就读这个长度的数据即可。这样收发就同步了哈哈!
然后:客户端就按照这个长度来读服务端一次发过来的信息。


还要解决一个问题就是 socket接收信息由字节转换成整型:
 Byte[] RecNum = new byte[4];
                        int iRevNum = netstream.Read(RecNum, 0, RecNum.Length);//读取客户发送来的字节信息。
                        int i = BitConverter.ToInt32(RecNum, 0);
                        i = System.Net.IPAddress.NetworkToHostOrder(i);


接下来就按i这么大来读信息就能同步了。具体代码见下:(网元监控中使用)

private void Read()
        {
            try
            {
                Byte[] Recp = new byte[1024];
                if (ClientSocket == null)
                {
                    return;
                }
                NetworkStream netstream = new NetworkStream(ClientSocket);
                int iRevp = netstream.Read(Recp, 0, Recp.Length);//读取客户发送来的信息。
                string strRevp = System.Text.Encoding.GetEncoding("gb2312").GetString(Recp, 0, iRevp);
                if (strRevp.IndexOf("请输入指令") != -1)
                {
                    string sendMsg = "";
                    if (curPort.Equals("ALL"))
                    {
                        sendMsg = "track " + curNet.NeENName + "\r\n";
                    }
                    else
                    {
                        sendMsg = "track " + curNet.NeENName + "#" + curPort + "\r\n";
                    }
                    DispatchMessage(sendMsg);
                }
                while (true)
                {
                    try
                    {
                        Byte[] RecNum = new byte[4];
                        int iRevNum = netstream.Read(RecNum, 0, RecNum.Length);//读取客户发送来的字节信息。
                        int i = BitConverter.ToInt32(RecNum, 0);
                        i = System.Net.IPAddress.NetworkToHostOrder(i);

                        Byte[] Rec = new byte[i];
                        int iRev = netstream.Read(Rec, 0, Rec.Length);//读取客户发送来的信息。
                        string strRev = System.Text.Encoding.GetEncoding("gb2312").GetString(Rec, 0, iRev);

                        strRev = strRev.Replace("\0", "");
                        ProcessReceiveData(strRev);
                    }
                    catch (Exception ex)
                    {
                        ;
                    }
                    Thread.Sleep(1000);
                }

            }
            catch (Exception ex)
            {
                ;
            }
        }

你可能感兴趣的:(socket 收发同步问题 解决方法)