/// <summary> /// 连接 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> public void Connect(string ip, Int32 port) { Preconditions.ThrowIfZeroOrMinus(port, "port"); IPAddress address; if (!IPAddress.TryParse(ip, out address)) { throw new ArgumentOutOfRangeException("ip"); } if (!_state.SetState(STATE_STARTED)) { return; } try { this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.socket.Connect(new IPEndPoint(address, port)); this.session = new ClientInnerSession(RaiseConnected, RaiseDisconnected, RaiseSended, RaiseReceived); this.session.Initialize(this.socket, this); this.session.Start(); } catch (Exception ex) { FreeResource(); throw ex; } }
private void FreeResource() { this.socket.Shutdown(SocketShutdown.Both); this.socket = null; this.session = null; _state.RemoveState(STATE_STARTED); _state.RemoveState(STATE_CLOSEING); }