public static void ReceiveCallback(IAsyncResult ar) { try { // A Socket to handle remote host communication. var handler = (Socket)ar.AsyncState; // The number of bytes received. var bytesRead = handler.EndReceive(ar); // Received message var content = Encoding.Unicode.GetString(buffer, 0, bytesRead); if (bytesRead > 0) { var message = new Message(content); if (message.Turn == -1) // New game { Console.WriteLine("New player has connected into {0}", message.RoomId); var room = rooms.GetOrAdd(message.RoomId, new Room()); // Check if room is full or not if (room.Count < 2) { room.Add(handler, message.Name); // Send to the client the player turn if (room.Count == 2) { int mapId = rand.Next(2); for (int index = 0; index < room.Count; index++) SendMessage(room.GetSocket(index), new Message { Turn = index, Name=room.GetName(index ^ 1), Col = mapId }); } } else { // The room is full message = new Message { Turn = -3 }; SendMessage(handler, message); } rooms.AddOrUpdate(message.RoomId, room, (key, existing) => { return room; }); } else if (message.Turn == -2) // Quit game { var room = rooms.GetOrAdd(message.RoomId, new Room()); if (room != null) { message = new Message { Turn = -2 }; SendMessage(handler, message); for (int index = 0; index < room.Count; index++) SendMessage(room.GetSocket(index), message); room.Clear(); } rooms.AddOrUpdate(message.RoomId, room, (key, existing) => { return room; }); } else { var room = rooms.GetOrAdd(message.RoomId, new Room()); if (room.Count == 2) { // Send the message to the other SendMessage(room.GetSocket(message.Turn ^ 1), message); } rooms.AddOrUpdate(message.RoomId, room, (key, existing) => { return room; }); } } // Continues to asynchronously receive data handler.BeginReceive( buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), handler ); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); } }
public static void SendMessage(Socket handler, Message message) { try { // Prepare the reply message var byteData = Encoding.Unicode.GetBytes(message.ToJSON()); handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); } }