/// <summary> /// 开始服务,连接服务端 /// </summary> public void StartClient() { try { //实例化 套接字 (ip4寻址协议,流式传输,TCP协议) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建 ip对象 IPAddress address = IPAddress.Parse(_ip); //创建网络节点对象 包含 ip和port IPEndPoint endpoint = new IPEndPoint(address, _port); //将 监听套接字 绑定到 对应的IP和端口 _socket.BeginConnect(endpoint, asyncResult => { try { _socket.EndConnect(asyncResult); //开始接受服务器消息 StartRecMsg(); HandleClientStarted?.Invoke(this); } catch (Exception ex) { HandleException?.BeginInvoke(ex, null, null); } }, null); } catch (Exception ex) { HandleException?.BeginInvoke(ex, null, null); } }
/// <summary> /// 开始服务,连接服务端 /// </summary> public bool StartClient() { try { //实例化 套接字 (ip4寻址协议,流式传输,TCP协议) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建 ip对象 IPAddress address = IPAddress.Parse(_ip); //创建网络节点对象 包含 ip和port IPEndPoint endpoint = new IPEndPoint(address, _port); //将 监听套接字 绑定到 对应的IP和端口 AutoResetEvent waitEvent = new AutoResetEvent(false); _socket.BeginConnect(endpoint, asyncResult => { try { _socket.EndConnect(asyncResult); //开始接受服务器消息 StartRecMsg(); HandleClientStarted?.Invoke(this); waitEvent.Set(); } catch (Exception ex) { AccessException(ex);; } }, null); waitEvent.WaitOne(); return(true); } catch (Exception ex) { AccessException(ex); return(false); } }