//发送信息给蛇 private static void wsSend_snakes(string str) { foreach (var socket in sever.m_asyncSocketList) { var snakeEntity = socket.snake; if (snakeEntity != null) { if (snakeEntity.State == 1) { if (socket.SendEventArgs.SocketError == SocketError.Success) { sever.PublicSend(socket.SendEventArgs, WebSocketClass.PackData(str)); } } } } }
private void ProcessAccept(SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { return; //异步处理失败,不做处理 } Interlocked.Increment(ref m_numConnectedSockets); Console.WriteLine("Client connection accepted. There are {0} clients connected to the server", m_numConnectedSockets); AsyncUserToken token = m_readWritePool.Pop(); ((AsyncUserToken)token).Socket = e.AcceptSocket; AsyncUserToken flag_usertoken = null; foreach (var m_asyncsocket in m_asyncSocketList) { if (((IPEndPoint)e.AcceptSocket.LocalEndPoint).Address.ToString() == ((IPEndPoint)m_asyncsocket.Socket.LocalEndPoint).Address.ToString()) { flag_usertoken = m_asyncsocket; } } if (flag_usertoken == null) { ((AsyncUserToken)token).snake.init_snake(); //添加到usertokenlist m_asyncSocketList.Add(token); bool willRaiseEvent = e.AcceptSocket.ReceiveAsync(token.ReceiveEventArgs); if (!willRaiseEvent) { lock (token) { ProcessReceive(token.ReceiveEventArgs); } } StartAccept(e); var dic = new Dictionary <string, string>(); dic["ip"] = ((IPEndPoint)token.Socket.LocalEndPoint).Address.ToString(); PublicSend(token.SendEventArgs, WebSocketClass.PackData(Json.funcObj2JsonStr(dic))); } else { ((AsyncUserToken)token).snake = flag_usertoken.snake; //移除掉线的 m_asyncSocketList.Remove(flag_usertoken); Interlocked.Decrement(ref m_numConnectedSockets); m_maxNumberAcceptedClients.Release(); Console.WriteLine("A client has been disconnected from the server. There are {0} clients connected to the server", m_numConnectedSockets); //添加到usertokenlist m_asyncSocketList.Add(token); bool willRaiseEvent = e.AcceptSocket.ReceiveAsync(token.ReceiveEventArgs); if (!willRaiseEvent) { lock (token) { ProcessReceive(token.ReceiveEventArgs); } } StartAccept(e); } }