public void StartClient() { logger.InfoFormat("begin start socket-client with address#{0}:{1}", ip, port); socketStarting = true; working = true; connectStatus = ConnectStatusEnum.CONNECTING; try { IPAddress ipAddr = IPAddress.Parse(ip); IPEndPoint remoteEP = new IPEndPoint(ipAddr, port); // Create a TCP/IP socket. _client = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. _client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), _client); while (connectStatus == ConnectStatusEnum.CONNECTING) { KK.Sleep(100); if (connectStatus == ConnectStatusEnum.CONNECT_FAILED) { break; } } socketStarting = false; logger.InfoFormat("connectStatus is {0}", connectStatus); logger.InfoFormat("end socket-client connect with address#{0}:{1}, _client#{2}", ip, port, _client); this.InvokeAfterSuccessConnected(); } catch (Exception e) { logger.Error("StartClient error", e); } finally { socketStarting = false; } // 无论何种情况,都应开启守护 if (EnableSocketGuard) { KeepAliveManager.ME.RestartGuard(this); } }
private void ConnectCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket client = (Socket)ar.AsyncState; // Complete the connection. client.EndConnect(ar); logger.InfoFormat("Socket connected to {0}", client.RemoteEndPoint.ToString()); connectStatus = ConnectStatusEnum.CONNECTED; } catch (Exception e) { logger.Error("ConnectCallback error.", e); connectStatus = ConnectStatusEnum.CONNECT_FAILED; } }
private static void SendNoticeConnect(bool IsConnect, ConnectStatusEnum tipMessageEnum) { NoticeConnectEvent(IsConnect, tipMessageEnum); }