public TcpClient(SocketManager socketManager) { maxBufferSize = 1024; ConnectTimeout = 5f; this.socketManager = socketManager; this.hearBeat = new HearBeat(socketManager, this); ConnectSuccess += hearBeat.Start; ConnectAbort += hearBeat.Stop; MsgManager.Instance.Regist(MsgID.ConnectSuccess, (data) => ConnectSuccess?.Invoke()); MsgManager.Instance.Regist(MsgID.ConnectFailed, (data) => ConnectFailed?.Invoke()); MsgManager.Instance.Regist(MsgID.ConnectAbort, (data) => ConnectAbort?.Invoke()); }
/// <summary> /// 连接完成回调 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void OnSocketAsyncCompleted(object sender, ISocketAsyncEventArgs e) { bool stopReceive = false; //是否停止数据接收 StateObject state = e.UserToken as StateObject; try { if (e.SocketError == SocketError.Success) { if (e.LastOperation == SocketAsyncOperation.Connect) { _connSuccess = true; ConnectSuccess?.Invoke(); } else if (e.LastOperation == SocketAsyncOperation.Receive) { if (state != null) { //服务器发来的消息 int length = e.BytesTransferred; state.EnqueueBufferQueue(length); //存储接受过来的数据 } } } else if (e.SocketError == SocketError.ConnectionReset) { System.Diagnostics.Debug.WriteLine(e.SocketError); stopReceive = true; SocketDisconnected?.Invoke(); } else if (e.SocketError == SocketError.ConnectionAborted || e.SocketError == SocketError.OperationAborted) { stopReceive = true; } else { stopReceive = true; } } catch (Exception ex) { if (ex is ObjectDisposedException) { stopReceive = true; return; //停止接收数据 } } finally { try { if (!stopReceive) { if (state != null) { //继续接收消息 e.SetBuffer(state.Buffer, 0, state.BufferSize); e.CurrentSocket.ReceiveAsync(e); } } else { e.Dispose(); e = null; state = null; CloseSocket(); } } catch (Exception ex) { if (!(ex is ObjectDisposedException)) { CloseSocket(); GC.Collect(); } } } }
private static extern IntPtr Theta_Connect(string ip_address, string game_object_name, ConnectSuccess success, ConnectError error);