首页 新闻 搜索 专区 学院

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

0
悬赏园豆:160 [已关闭问题] 关闭于 2018-10-22 16:01

我用C#写的程序,放到PDA中运行,其中有和工控机通讯,扫描次数增多就会报出错。
一开始是报

百度后 需要安装NETCFv35.Messages.zh-CHS.cab,
然后不报错误,开始报Sicket的问题 如图

我仔细查看我的代码没有问题。Sicket该关闭的关闭了。
我PDA上的代码我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 });
            }
        }
Liwuyi的主页 Liwuyi | 初学一级 | 园豆:-100
提问于:2015-06-29 22:06
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册