୧((〃•̀ꇴ•〃))૭⁺✧ 2021-07-07 14:01 采纳率: 72.7%
浏览 246
已结题

C# socket异步通讯客户端第一次能接收到数据,第二次接收不到

 //创建 1个客户端套接字 和1个负责监听服务端请求的线程  
        public static Socket socketClient = null;

        Thread threadClient = null;

        int ConnectionResult = -2;

        static Dictionary<string, ServiceState> dic_ip = new Dictionary<string, ServiceState>();

        public FTitlePage1()
        {
            InitializeComponent();
            ConnectionSocket();
        }


        /// <summary>
        /// 开启socket连接
        /// </summary>
        public void ConnectionSocket()
        {
            try
            {
                Start();
                threadClient = new Thread(MonitorSocker);
                threadClient.IsBackground = true;
                threadClient.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " " + ex.StackTrace);
            }

        }


        /// <summary>
        /// 连接服务端
        /// </summary>
        private void Connect(IAsyncResult ar)
        {
            try
            {
                ServiceState obj = new ServiceState();
                Socket client = ar.AsyncState as Socket;
                obj.serviceSocket = client;

                //获取服务端信息
                client.EndConnect(ar);

                //添加到字典集合
                if (dic_ip.ContainsKey("192.168.0.81:4001"))
                {
                    dic_ip.Remove("192.168.0.81:4001");
                }


                dic_ip.Add(client.RemoteEndPoint.ToString(), obj);

                //接收连接Socket数据 
                client.BeginReceive(obj.buffer, 0, ServiceState.bufsize, SocketFlags.None, new AsyncCallback(ReadCallback), obj);

                ConnectionResult = 0;
            }
            catch (SocketException ex)
            {
                ConnectionResult = ex.ErrorCode;
                Console.WriteLine(ex.Message + " " + ex.StackTrace);
            }
        }


        /// <summary>
        /// 数据接收
        /// </summary>
        private void ReadCallback(IAsyncResult ar)
        {
            ServiceState obj = ar.AsyncState as ServiceState;
            Socket s_socket = obj.serviceSocket;

            try
            {
                if (s_socket.Connected)
                {
                    //接收数据处理
                    int bytes = s_socket.EndReceive(ar);
                    if (bytes != 99)
                    {
                        ShowErrorNotifier("数据接收不完整");
                        return;
                    }
                    byte[] data = obj.buffer;   

                }

            }
            catch (SocketException ex)
            {
                ConnectionResult = ex.ErrorCode;
                Console.WriteLine(ex.Message + " " + ex.StackTrace);
            }

        }

        /// <summary>
        /// 发送数据
        /// </summary>
        private void Send(Socket s_socket, byte[] by)
        {
            try
            {
                //发送
                s_socket.BeginSend(by, 0, by.Length, SocketFlags.None, asyncResult =>
                {
                    try
                    {
                        
                        //完成消息发送
                        int len = s_socket.EndSend(asyncResult);
                    }
                    catch (SocketException ex)
                    {
                        ConnectionResult = ex.ErrorCode;
                        Console.WriteLine(ex.Message + " " + ex.StackTrace);
                    }
                }, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + " " + ex.StackTrace);
            }
        }





        /// <summary>
        /// 连接socket
        /// </summary>
        public void Start() 
        {
            try
            {
                string ip = "192.168.0.81";
                int port = int.Parse("4001");
                var endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socketClient.BeginConnect(endPoint, new AsyncCallback(Connect), socketClient);
            }
            catch (SocketException ex)
            {
                Console.WriteLine("error ex=" + ex.Message + " " + ex.StackTrace);
            }
        }

        //监听Socket
        void MonitorSocker()
        {
            while (true)
            {
                if (ConnectionResult != 0 && ConnectionResult != -2)//通过错误码判断
                {
                    Start();
                    dic_ip = new Dictionary<string, ServiceState>();
                }
                Thread.Sleep(1000);
            }
        }

    

 private void uiButton1_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[8];
            data[0] = 0x01;
            data[1] = 0x04;
            data[2] = 0x00;
            data[3] = 0x00;
            data[4] = 0x00;
            data[5] = 0x2f;
            data[6] = 0xd6;
            data[7] = 0xb1;
            Send(dic_ip["192.168.0.81:4001"].serviceSocket,data);
        }

我在登陆后就在初始化那里进行连接了设备,然后点击按钮发送指令,第一次可以获取数据,第二次就不行了,不走ReadCallback方法了,这是什么原因?求大佬解惑

  • 写回答

1条回答 默认 最新

  • sanyuni 2021-07-09 15:08
    关注

    ReadCallback里面调用EndReceive没有再调用BeginReceive

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 8月13日

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)