Socket

来源:互联网 发布:ubuntu mv 移动文件夹 编辑:程序博客网 时间:2024/05/22 12:22
 //开始连接如果断开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);
            }
        }

原创粉丝点击