//连接IP端口 public void Connect(string ip, ushort port) { this.IPAddr_ = ip; this.Port_ = port; if (this.NativeSocket_ == null) { //创建新的socket this.NativeSocket_ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.NativeSocket_.ReceiveBufferSize = this.BufferMaxSize; this.NativeSocket_.NoDelay = true; } else { //socket已连接,不再连接 if (this.NativeSocket_.Connected) { return; } } IPAddress ipAddr = IPAddress.Parse(this.IPAddr_); IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, this.Port_); IAsyncResult result = this.NativeSocket_.BeginConnect(ipEndPoint, new AsyncCallback(OnConnectResult), this.NativeSocket_); //连接采用异步方式 //超时 bool success = result.AsyncWaitHandle.WaitOne(5000, true); if (!success) { Debug.LogError("连接超时"); this.SocketState_ = e_SocketState.SCK_CONNECT_OUTTIME; } Debug.Log("启动链接网络 " + this.IPAddr_ + ":" + this.Port_ + "!"); }
//异步连接完成后执行 private void OnConnectResult(IAsyncResult result) { lock (this.socketLock_) { try { if (null == result) { return; } Socket nativeSocket = (Socket)result.AsyncState; if (null == nativeSocket) { return; } nativeSocket.EndConnect(result); //获取到BeginConnect的socket后,调用EndConnect完成连接尝试 if (nativeSocket.Connected) { //连接成功,创建接收线程 this.SocketState_ = e_SocketState.SCK_CONNECT_SUCCESS; this.RecvThread_ = new Thread(new ThreadStart(ProcessAsyncRecv)); this.RecvThread_.IsBackground = true; this.RecvThread_.Start(); Debug.LogError("connect " + this.IPAddr_ + ":" + this.Port_ + " success!"); } else { Debug.Log("连接失败"); this.SocketState_ = e_SocketState.SCK_CONNECT_FAIL; } } catch (Exception e) { Debug.LogError("连接异常:" + e.Message); this.SocketState_ = e_SocketState.SCK_CONNECT_EXCEPTION; DisConnect(); } } }
//连接成功后,处理异步收取数据的线程 private void ProcessAsyncRecv() { while (true) { try { if (null == this.NativeSocket_) { this.SocketState_ = e_SocketState.SCK_CLOSED; break; } if (!this.NativeSocket_.Connected) { this.NativeSocket_.Close(); this.SocketState_ = e_SocketState.SCK_CLOSED; break; } try { byte[] buffer = new byte[4096]; //ProcessAsyncRecv方法中会一直等待服务端回发消息 //如果没有回发会一直在这里等着。 int buffSize = this.NativeSocket_.Receive(buffer); if (buffSize <= 0) { DisConnect(); break; } if (buffer.Length > 0) { SplitPackage(buffer, buffSize); } } catch (SocketException ex) { Debug.LogError(ex); DisConnect(); break; } } catch (Exception e) { Debug.LogError(e.Message); DisConnect(); break; } } }
//断开Socket连接 public void DisConnect() { lock (this.socketLock_) { try { if (null != this.NativeSocket_) { this.NativeSocket_.Close(); this.NativeSocket_ = null; } this.RecvThread_ = null; } catch { this.RecvThread_ = null; this.NativeSocket_ = null; } this.SocketState_ = e_SocketState.SCK_CLOSED; } }