C#中Socket的Connect(),Disconnect()的坑

最近在做Unity端和服务端的Socket连接,照着网上的案例码自己的代码,遇到了很多坑,其中消耗我最多时间,并且网上找了好久都没找到答案的一个坑,这里说一下

----------------------------------------------------------------------------------------------------------------------

我连接服务端,用的都是Socket的Connect()方法(看的百度的案例。。。中坑了),然后出现了,会疯狂的报错

 

/// <summary>
        /// 连接socket,断开后的一段时间,尝试重连
        /// </summary>
        void Reconnection()
        {
            while (isCheckConnect)
            {
                try
                {

                    if ((DateTime.Now - lastHeartTime).Seconds > maxHeartInterval && SocketInstance.Connected)
                    {
                        SocketInstance.Disconnect(false);
                    }
                    Debug.Log(socketInstance.Connected);
                    if (!SocketInstance.Connected)
                    {
                        Debug.Log("开始连接" + SocketInstance.Connected);
                        //mainContext.Post((a) => { ConnectSocket(); }, null);
                        IPAddress ipaddress = IPAddress.Parse(ipadd);
                        IPEndPoint endpoint = new IPEndPoint(ipaddress, prot);
                        SocketInstance.Connect(endpoint);
                        if (SocketInstance.Connected)
                        {
                            SocketInstance.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveData), SocketInstance);
                            //心跳的线程

                            if (dictThread.ContainsKey("SendHeart"))
                            {
                                dictThread["SendHeart"].Abort();
                                dictThread.Remove("SendHeart");
                            }
                            Thread sendHeartThread = new Thread(new ThreadStart(SendHeart));
                            sendHeartThread.IsBackground = true;
                            dictThread.Add("SendHeart", sendHeartThread);
                            sendHeartThread.Start();
                            //数据处理的线程

                            if (dictThread.ContainsKey("ProcessMsg"))
                            {
                                dictThread["ProcessMsg"].Abort();
                                dictThread.Remove("ProcessMsg");
                            }
                            Thread processMsgThread = new Thread(new ThreadStart(ProcessMsg));
                            processMsgThread.IsBackground = true;
                            dictThread.Add("ProcessMsg", processMsgThread);
                            processMsgThread.Start();

                            var a = new RegisterCommand();
                            SendCommand(a, 03);
                        }
                    }


                }
                catch (Exception ex)
                {
                    Debug.LogError(ex.Message);
                }
                Thread.Sleep((int)(reconnectionInterval * 1000));
            }
            Debug.Log("我这线程结束了");
        }

由于我是在UnityEditor下运行的,打开unity直接连接socket并进行相关操作,所以测试起来和排查起来比较麻烦,用了各种能想到的方法测试,具体过程略过,直接说结果

问题出在Socket.Connected属性,Socket.Connected的改变时刻是在Connect()和Disconnect()方法调用的瞬间,而不是Socket完全断开或者连接的时候,Connect()和Disconnect()是需要是时间的,而且这个时间还和网络环境等因素有关,所以会出现,我判断 if (!SocketInstance.Connected)的时候出现是断连状态,但是进入里面进行重连的时候,又提示Socket已经连接,因为Disconnect()还在执行中,还未完成

最后建议:大家用Socket连接的时候,用BeginConnect()和BeginDisconnect()这两个方法可以加回调事件,来监听连接和断连完成,网上大多数教程,只是叫你简单的连接,却不适合用在正式项目中,项目中要考虑,断线重连等等状况,所以带完成回调的方法,更加适合我们来控制Socket的过程

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Android,可以使用Bluetooth Low Energy(BLE)API扫描、连接和断开连接BLE设备。以下是一些基本步骤: 1. 获取 BluetoothAdapter 对象:使用 BluetoothManager 获取 BluetoothAdapter 对象。 ```java BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); ``` 2. 检查蓝牙是否已启用:使用 isEnabled() 方法检查蓝牙是否已启用。 ```java if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } ``` 3. 开始扫描:使用 startScan() 方法开始扫描BLE设备。可以使用 BluetoothLeScanner 对象进行扫描。 ```java BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner(); scanner.startScan(mScanCallback); ``` 4. 停止扫描:使用 stopScan() 方法停止扫描BLE设备。 ```java scanner.stopScan(mScanCallback); ``` 5. 连接设备:使用 BluetoothDevice 对象连接BLE设备。可以使用 connectGatt() 方法进行连接。 ```java BluetoothGatt mBluetoothGatt = bluetoothDevice.connectGatt(this, false, mGattCallback); ``` 6. 断开连接:使用 disconnect() 方法断开连接。 ```java mBluetoothGatt.disconnect(); ``` 7. 关闭 GATT 连接:使用 close() 方法关闭 GATT 连接。 ```java mBluetoothGatt.close(); ``` 以上是一些基本步骤来扫描、连接和断开连接BLE设备。具体实现还需要根据具体需求进行调整和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值