// This method is invoked when an asynchronous send operation completes. // The method issues another receive on the socket to read any additional // data sent from the client // // <param name="e"></param> private void ProcessSend(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { // done echoing data back to the client AsyncUserToken token = (AsyncUserToken)e.UserToken; // read the next block of data send from the client bool willRaiseEvent = token.Socket.ReceiveAsync(e); if (!willRaiseEvent) { ProcessReceive(e); } } else { CloseClientSocket(e); } }
private void btnSend_Click(object sender, EventArgs e) { if (m_socket.ClientList.Count > 0) { AsyncUserToken token = null; // 查找要发送的client的socket对象。zhx token = m_socket.ClientList.Find(x => x.IPAddress.ToString() == "127.0.0.1"); //foreach (AsyncUserToken usertoken in m_socket.ClientList) //{ // if (usertoken.IPAddress.ToString() == "192.168.1.158") // { // token = usertoken; // break; // } //} string message = this.send.Text.Trim(); if (string.IsNullOrWhiteSpace(message)) { MessageBox.Show("请输入要发送的内容", "提示", MessageBoxButtons.OK); return; } else { if (token != null) { byte[] messageBuffer = Encoding.UTF8.GetBytes(this.send.Text); bool issent = m_socket.SendMessage(token, messageBuffer); if (issent) { this.textBoxSend.AppendText("Send: " + message + "\r\n"); } } } } else { MessageBox.Show("未监听到连接,无法发送", "提示", MessageBoxButtons.OK); return; } }
private void ProcessAccept(SocketAsyncEventArgs e) { try { Interlocked.Increment(ref m_clientCount); // Get the socket for the accepted client connection and put it into the //ReadEventArg object user token SocketAsyncEventArgs readEventArgs = m_pool.Pop(); AsyncUserToken userToken = (AsyncUserToken)readEventArgs.UserToken; userToken.usernamr = "Mtt"; userToken.Socket = e.AcceptSocket; userToken.ConnectTime = DateTime.Now; userToken.Remote = e.AcceptSocket.RemoteEndPoint; userToken.IPAddress = ((IPEndPoint)(e.AcceptSocket.RemoteEndPoint)).Address; lock (m_clients) { m_clients.Add(userToken); } if (ClientNumberChange != null) { ClientNumberChange(1, userToken); } if (!e.AcceptSocket.ReceiveAsync(readEventArgs)) { ProcessReceive(readEventArgs); } } catch (Exception me) { Console.WriteLine(me.Message); } // Accept the next connection request if (e.SocketError == SocketError.OperationAborted) { return; } StartAccept(e); }
/// <summary> /// 停止服务 /// </summary> public void Stop() { foreach (var item in m_clients) { try { AsyncUserToken token = item; token.Socket.Shutdown(SocketShutdown.Both); } catch (Exception) { } } try { if (m_clients.Count > 0) { listenSocket.Shutdown(SocketShutdown.Both); } } catch (Exception e)//当socket 无连接时(即没有可用已连接的client) { // listenSocket.Disconnect(false);///因为无可用的socket连接,此方法不可用 Console.WriteLine(e.Message); } finally { listenSocket.Close(); //通知界面,server已经停止 if (ServerStopedEvent != null) { ServerStopedEvent(); } lock (m_clients) { m_clients.Clear(); } } }