/// <summary> /// Connect to server /// </summary> /// <param name="millisecondsTimeout">connect timeout, in millisecond</param> /// <param name="setThreadAffinityMask">need set the thread affinity mask</param> public void Connect(int millisecondsTimeout, bool setThreadAffinityMask) { lock (_ConnectLock) { if (Connected) { return; } else { Disconnect(); } if (millisecondsTimeout < 0) { throw new ArgumentException("milliseconds can't be negative"); } InitVar(); _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _Socket.Bind(this.BindIPEndPoint); _Socket.BeginConnect(this.RemoteIPEndPoint, Async_Connection, _Socket); if (!_ConnectEvent.WaitOne(millisecondsTimeout)) { Disconnect(); throw new NTcpException(string.Format("Try to connect to remote server {0} timeout", this.RemoteIPEndPoint), ErrorCode.ConnectTimeout); } else if (_ConnectException != null) { Disconnect(); throw _ConnectException; } _Socket.NoDelay = true; _Socket.SendBufferSize = 16 * 1024; _SCB = new SCB(_Socket); _SCB.OnReceive = OnReceiveEvent; _SCB.OnError = OnErrorEvent; _SCB.OnDisconnect = OnDisconnectEvent; _SendMessageQueue = new SendMessageQueue(OnReadyToSend, setThreadAffinityMask); Connected = true; } }
/// <summary> /// Connect to server /// </summary> /// <param name="timeout">connect timeout, in seconds</param> public void Connect(int timeout) { _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _Socket.Bind(this.BindIPEndPoint); _Socket.Connect(this.RemoteIPEndPoint); _Socket.NoDelay = true; _Socket.SendBufferSize = 16 * 1024; _SCB = new SCB(_Socket); _SCB.OnReceive = OnReceiveEvent; _SendMessageQueue = new SendMessageQueue(OnReadyToSend); Connected = true; }
private void InitVar() { _ConnectEvent = new AutoResetEvent(false); _ConnectException = null; _SCB = null; _Socket = null; _SendMessageQueue = null; _Connected = false; _Closed = false; _ChannelSync = new object(); _CurChannel = 0; _SyncMessageLock = new object(); _SyncMessageDict = new Dictionary <uint, SyncBlock>(); }
/// <summary> /// /// </summary> public void Disconnect() { try { Connected = false; if (_SendMessageQueue != null) { if (!_SendMessageQueue.Closed) { _SendMessageQueue.Close(); } } } catch { } try { ClearChannelForSync(); } catch { } try { if (_SendMessageQueue != null) { try { if (!_SendMessageQueue.Join(10000)) { _SendMessageQueue.Abort(); } } catch { _SendMessageQueue.Abort(); } } } catch { } try { if (_Socket != null) { _Socket.Close(); } } catch { } finally { _SendMessageQueue = null; _Socket = null; } }