public override void Connect(string host, int port) { try { if (IsConnected) { CloseSocket(); } IPAddress[] address = Dns.GetHostAddresses(host); socket = new Socket(address[0].AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); Trace.Instance.debug("BeginConnect. host = {0}, port = {1}", address[0].ToString(), port); socket.BeginConnect(address, port, new AsyncCallback(HandleConnect), socket); } catch (Exception e) { Trace.Instance.error("connect throw exception. host = {0}, port = {1}, exception = {2}", host, port, e.Message); PostOptionMsgEvent?.Invoke(new ConnectMsg(false)); } }
private void HandleConnect(IAsyncResult result) { ConnectMsg msg = new ConnectMsg(false); try { Socket _socket = (Socket)result.AsyncState; _socket.EndConnect(result); if (_socket.Connected) { msg.Success = true; BeginReceive(); } } catch (Exception e) { Trace.Instance.warn("HandleConnect throw exception. exception = {0}", e.Message); CloseSocket(); } finally { PostOptionMsgEvent?.Invoke(msg); } }