private void OnAccept(IAsyncResult ar) { if (m_socket == null) { return; } Socket server_socket = (Socket)ar.AsyncState; ar.AsyncWaitHandle.Close(); try { //初始化一个SOCKET,用于其它客户端的连接 Socket client_socket = server_socket.EndAccept(ar); lock (m_sync_lock) { long conn_idx = ++m_share_conn_idx; UserToken token = m_user_tokens_pools.Spawn(); token.ConnId = conn_idx; token.Socket = client_socket; m_user_tokens.Add(conn_idx, token); if (OnOpen != null) { OnOpen(conn_idx); } //连接成功,有可能被踢出,需要再次判断是否有效 if (m_user_tokens.ContainsKey(conn_idx)) { SendRecvBuffer buffer = m_buffer_pools.Spawn(); buffer.ConnId = token.ConnId; buffer.Socket = token.Socket; BeginReceive(buffer); } //等待新的客户端连接 server_socket.BeginAccept(new AsyncCallback(OnAccept), server_socket); } } catch (Exception e) { Log.Exception(e); this.Close(); return; } }
public void Send(byte[] message, int offset, int count) { if (m_socket == null || !m_socket.Connected || message == null) { return; } SendRecvBuffer buffer = m_buffer_pools.Spawn(); buffer.Socket = m_socket; System.Array.Copy(message, offset, buffer.Buffer, 0, count); try { buffer.Socket.BeginSend(buffer.Buffer, 0, count, 0, new AsyncCallback(OnSend), buffer); } catch (Exception e) { Log.Error("发送失败:" + e.Message); this.Close(); } }