Socket

 //开始连接如果断开1秒1连
       private void InitSocket()
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(IPAddress.Parse(ip), 8099);
                AsyncReveive();
            }
            catch (Exception)
            {
                MessageBox.Show("失败,尝试重新连接");
                ConnectServer = new DispatcherTimer();
                ConnectServer.Interval = TimeSpan.FromSeconds(1);
                succee = false;
                ConnectServer.Tick += (e, f) =>
                {
                    try
                    {
                        if (succee == false)
                        {
                            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                            socket.Connect(IPAddress.Parse(ip), 8099);
                            ConnectServer.Stop();
                            ConnectServer = null;
                            succee = true;
                        }
                    }
                    catch (Exception)
                    {


                    }


                };
                ConnectServer.Start();
            }

        }

  private void AsyncReveive()
        {
            byte[] data = new byte[1024];
            try
            {
                //开始接收消息  
                socket.BeginReceive(data, 0, data.Length, SocketFlags.None,
                IAsyncResult =>
                {
                    try
                    {
                        int length = socket.EndReceive(IAsyncResult);
                        if (length > 0)
                        {
                            content = Encoding.UTF8.GetString(data);
                            content = content.TrimEnd('\0');
                            this.Dispatcher.BeginInvoke((Action)(() =>
                            {
                                InitConent();
                            }));                         
                            AsyncReveive();
                        }
                        //else
                        //    dispose();
                    }
                    catch (Exception)
                    {
                        //进入异常后重新连接
                        InitSocket();
                    }


                }, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值