C# 开发WinCE 6.0 Socket 问题 解答 困扰好久了

.Net技术 码拜 4年前 (2016-02-29) 675次浏览
本人用C#写的程序,放到PDA中运行,其中有和工控机通讯,扫描次数增多就会报出错。
一开始是报C# 开发WinCE 6.0 Socket 问题 解答 困扰好久了
百度后 需要安装NETCFv35.Messages.zh-CHS.cab,
然后不报错误,开始报Sicket的问题 如图C# 开发WinCE 6.0 Socket 问题 解答 困扰好久了
本人仔细查看本人的代码没有问题。Sicket该关闭的关闭了。
本人PDA上的代码

try
            {
                Loading("正在处理扫描数据...",true);
             
                    //发送消息
                    string msg = string.Format("{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}",
                        tabEquipList.TabPages[cur].Tag.ToString(), barcode,
                        txtDateList[cur].Text, txtSftList[cur].Tag.ToString(), txtGrpList[cur].Tag.ToString(),
                        matid,leftOrRight, result);
                    Loading("正在连接消息服务器...",true);
                    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    socket.Connect(serverIp);
                    Loading("正在发送消息...", true);
                    socket.Send(Encoding.Default.GetBytes(msg));
                    //接收消息
                    if (result == "验证通过")
                    {
                        byte[] byteMessage = new byte[256];
                        Loading("正在等待反馈...", true);
                        //启动心脏计数器
                        StartHeart();
                        int rec = socket.Receive(byteMessage);//等待服务器反馈消息
                        recFlag = true;
                        if (rec > 0)
                        {
                            lblMsgList[cur].Text = Encoding.Default.GetString(byteMessage, 0, byteMessage.Length);
                            if (lblMsgList[cur].Text.Contains("成功"))
                            {
                                scanCount -= 1;//可用的扫描次数减一
                                if (leftOrRight == "L")
                                {
                                    txtLeftBarCodeList[cur].Text = barcode;
                                    txtLeftBarCodeList[cur].ForeColor = Color.Red;
                                    txtLeftBarCodeList[cur].ForeColor = System.Drawing.Color.Black;
                                    lblScanMsg.BackColor = Color.Green;
                                    lblScanMsg.Visible = true;
                                }
                                else
                                {
                                    txtRightBarCodeList[cur].Text = barcode;
                                    txtRightBarCodeList[cur].ForeColor = Color.Red;
                                    txtRightBarCodeList[cur].ForeColor = System.Drawing.Color.Black;
                                    this.lblScanMsg.BackColor = Color.Blue;
                                    this.lblScanMsg.Visible = true;
                                }
                                PlaySound("添加成功.wav");
                            }
                        }
                    }
                    else
                    {
                        lblMsgList[cur].Text = result.Trim();
                       // PlaySound(result+".wav");
                        PlaySound("Error.wav");
                    }
                }
            }
            catch(Exception ex)
            {
                MsgHelper.ShowMsg("出错啦!"+ex.Message.ToString());
                PlaySound("Error.wav");
                //lblMsgList[tabEquipList.SelectedIndex].Text = "出错啦!" + ex.Message.ToString();
            }
            finally
            {
               
                if (socket != null)
                    socket.Close();
                WcfSystem.DisposeWcf();
                EndLoading("");
            }
  int count = 0;
        public void StartHeart()
        {
            count = 0;
            recFlag = false;
            heart = new System.Threading.Timer(new System.Threading.TimerCallback(StartHeart_CallBack), null, 0, 1000);
        }
        private void StartHeart_CallBack(object sender)
        {
            count++;
            if (count >= 30)
            {
                if (recFlag == false)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    heart.SafeDispose();
                }
            }
        }

工控机上的代码:

        public CuringProMain thisf = null;             //操作窗口
        public Socket listener;                   //申明一个套接
        public delegate void DelegateWriteScanResult(string barcode, string result, bool isWriteToLog);
        public MySocket(CuringProMain thisf)
        {
            this.thisf = thisf;
        }
        //侦听方法
        public void Listen()
        {
            try
            {
                int nPort = 56789;
                //获取本地Ip
                IPAddress ServerIp = PublicVar.Common.GetIP();
                IPEndPoint iep = new IPEndPoint(ServerIp, nPort);////ip地址和端口号组成的
                listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //定义套接字类型;      
                listener.Bind(iep);//绑定ip和端口;
                listener.Listen(10);
                listener.BeginAccept(new AsyncCallback(AcceptCallBack), listener);
                //Accept_Async();
            }
            catch (Exception ex)
            {
                PublicVar.Common.writeLog("创建客户端连接失败!" + ex.Message.ToString());
            }
        }
        private void AcceptCallBack(IAsyncResult ar)
        {
            try
            {
                if (isRun)
                {
                    listener.BeginAccept(new AsyncCallback(AcceptCallBack), listener);
                    Socket sok = (Socket)ar.AsyncState;
                    Socket client = sok.EndAccept(ar);
                    StateObject state = new StateObject();
                    state.workSocket = client;
                    client.BeginReceive(state.bytedata, 0, StateObject.bufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
            }
            catch (Exception ex)
            {
                //thisf.Invoke(new DelegateWriteScanResult(thisf.WriteScanResult), new object[] { "", "创建客户端连接失败!" + ex.Message.ToString(), true });
            }
        }
//异步接收回调函数
        public void ReadCallback(IAsyncResult ar)
        {
            StateObject state = null;
            Socket handler = null;
            string msg = "1";
            try
            {
                state = (StateObject)ar.AsyncState;
                handler = state.workSocket;
                int bytesRead = handler.EndReceive(ar);
                if (bytesRead > 0)
                {
                    string strmsg = Encoding.Default.GetString(state.bytedata, 0, bytesRead);
                    state.sb.Append(strmsg);
                    msg = state.sb.ToString();
                    string result = "";
                        //处理扫描的
                        result = thisf.DealScanBarCode(msg);
                        if (result != "11")
                        {
                            //反馈处理结果
                            byte[] bf;
                            bf = Encoding.Default.GetBytes(result);
                            handler.Send(bf, SocketFlags.None);
                        }
                        else
                        {
                            handler.Close();
                        }
                }
                else
                {
                    handler.BeginReceive(state.bytedata, 0, StateObject.bufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
            }
            catch (Exception ex)
            {
                thisf.Invoke(new DelegateWriteScanResult(thisf.WriteScanResult), new object[] { "", "接收或反馈消息失败!消息内容:" + msg + ex.Message.ToString(), true });
                try
                {
                    //反馈处理结果
                    byte[] bf;
                    bf = Encoding.Default.GetBytes("扫描失败!" + ex.Message.ToString());
                    handler.Send(bf, SocketFlags.None);
                }
                catch
                {
                }
            }
        }
        //异步发送
        private void Send(Socket handler, string data)
        {
            byte[] byteData = Encoding.Default.GetBytes(data);
            handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
        }
        //异步发送回调函数
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket handler = (Socket)ar.AsyncState;
                int bytesSent = handler.EndSend(ar);
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception ex)
            {
                thisf.Invoke(new DelegateWriteScanResult(thisf.WriteScanResult), new object[] { "", "反馈消息失败!" + ex.Message.ToString(), true });
            }
        }
解决方案

50

引用 4 楼 liweuyi 的回复:

没有人回答么?

看本人写的一篇关于粘包的处理
http://www.cnblogs.com/wangjun8868/p/4380187.html
正好实用你这个场景

50

引用 10 楼 liweuyi 的回复:
Quote: 引用 5 楼 wangjun8868 的回复:
Quote: 引用 4 楼 liweuyi 的回复:

没有人回答么?

看本人写的一篇关于粘包的处理
http://www.cnblogs.com/wangjun8868/p/4380187.html
正好实用你这个场景

本人现在的这个错误是 远程主机被强行关闭 和数据发生粘包有关系么?
本人怎么确定是发生了粘包呢?

这个错误是原因是服务器端报错了,服务器断开 了,导致客户端报的这个错,你最好在服务器端断点一下
用Console.Write() 输出strmsg (非DEBUG下)
string strmsg = Encoding.Default.GetString(state.bytedata, 0, bytesRead);
看收到的数据是不是粘包了,假如粘包了,数据要么少了要么多了很多


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C# 开发WinCE 6.0 Socket 问题 解答 困扰好久了
喜欢 (0)
[1034331897@qq.com]
分享 (0)