/// <summary> /// 连接服务器 /// </summary> /// <param name="ip">服务器 IP</param> /// <param name="port">端口</param> /// <param name="process">数据流处理接口</param> public void Connect(string ip, int port, ISocketProcess process) { try { this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), (IAsyncResult asyncResult) => { try { this.socket.EndConnect(asyncResult); } catch { throw; } }, null); this.helper = new SocketReceiveHelper(null, this, this.socket, null, process, () => { SocketHelper.Close(this.socket); }); this.helper.Receive(); } catch { SocketHelper.Close(this.socket); throw; } }
public SocketReceiveHelper(SocketServerHelper serverHelper, SocketClientHelper clientHelper, Socket socket, string key, ISocketProcess process, Action closeCallback) { this.serverHelper = serverHelper; this.clientHelper = clientHelper; this.socket = socket; this.process = process; this.key = key; this.closeCallback = closeCallback; }
/// <summary> /// /// </summary> /// <param name="ip">服务器 IP</param> /// <param name="port">端口</param> /// <param name="process">数据流处理接口</param> /// <param name="maxClientCount">客户端最大连接数</param> public SocketServerHelper(string ip, int port, ISocketProcess process, int maxClientCount = int.MaxValue) { try { this.process = process; this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port)); this.socket.Listen(maxClientCount); } catch { SocketHelper.Close(this.socket); throw; } }
public SocketThreadHelper(SocketServerHelper helper, string key, Socket socket, ISocketProcess process, Action <Socket> closeCallback) { this.socket = socket; this.helper = new SocketReceiveHelper(helper, null, socket, key, process, () => { if (closeCallback != null) { closeCallback(socket); } }); }