posts - 124,  comments - 29,  trackbacks - 0
首先:服务端要发四个字节过来,代表接下来他发了多少数据过来,然后每次客户端就读这个长度的数据即可。这样收发就同步了哈哈!
然后:客户端就按照这个长度来读服务端一次发过来的信息。


还要解决一个问题就是 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)
            {
                ;
            }
        }
posted on 2010-01-07 11:34 天书 阅读(930) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2010年1月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(5)

随笔档案

文章分类

文章档案

好友的Bolg

搜索

  •  

最新评论

阅读排行榜

评论排行榜