/// <summary> /// 触发网络错误事件 /// </summary> /// <param name="state"></param> private void RaiseNetError(SocketClientHandle handle) { if (NetError != null) { NetError(this, new SocketEventArgs(handle)); } }
/// <summary> /// 开始进行监听 /// </summary> private void StartListen() { _serverSock.Listen(1024); SocketClientHandle handle; while (IsRunning) { if (_clientCount >= _maxClient) { //TODO 客户端过多异常 RaiseOtherException(null); } else { Socket clientSock = _serverSock.Accept(); _clientCount++; IPEndPoint ip = (IPEndPoint)clientSock.RemoteEndPoint; Console.WriteLine("获取到来自{0} : {1}的连接", ip.Address, ip.Port); //TODO 创建一个处理客户端的线程并启动 handle = new SocketClientHandle(clientSock); _clients.Add(handle); //使用线程池来操作 ThreadPool.QueueUserWorkItem(new WaitCallback(handle.RecevieData)); //Thread pthread; //pthread = new Thread(new ThreadStart(client.RecevieData)); //pthread.Start(); //这里应该使用线程池来进行 } } }
private void RaiseDataReceived(SocketClientHandle handle) { if (DataReceived != null) { DataReceived(this, new SocketEventArgs(handle)); } }
/// <summary> /// 触发数据发送事件 /// </summary> /// <param name="state"></param> private void RaiseCompletedSend(SocketClientHandle handle) { if (CompletedSend != null) { CompletedSend(this, new SocketEventArgs(handle)); } }
/// <summary> /// 触发异常事件 /// </summary> /// <param name="state"></param> private void RaiseOtherException(SocketClientHandle handle, string descrip) { if (OtherException != null) { OtherException(this, new SocketEventArgs(descrip, handle)); } }
/// <summary> /// 触发客户端连接事件 /// </summary> /// <param name="state"></param> private void RaiseClientConnected(SocketClientHandle handle) { if (ClientConnected != null) { ClientConnected(this, new SocketEventArgs(handle)); } }
/// <summary> /// 关闭一个与客户端之间的会话 /// </summary> /// <param name="handle">需要关闭的客户端会话对象</param> public void Close(SocketClientHandle handle) { if (handle != null) { _clients.Remove(handle); handle.Dispose(); _clientCount--; //TODO 触发关闭事件 } }
private void RaiseOtherException(SocketClientHandle handle) { RaiseOtherException(handle, ""); }
/// <summary> /// 发送函数 /// </summary> public void Send(string msg, SocketClientHandle client) { //TODO }
public SocketEventArgs(string msg, SocketClientHandle handle) { this._msg = msg; this._handle = handle; IsHandled = false; }
public SocketEventArgs(SocketClientHandle handle) { this._handle = handle; IsHandled = false; }