public static BaseMessage Receive(NetworkStream networkStream, int spectedMessageType) { Console.WriteLine("ReceiveMessage()"); IFormatter formatter = new BinaryFormatter(); try { Message.BaseMessage message = (Message.BaseMessage)formatter.Deserialize(networkStream); if (message.Type != spectedMessageType) { throw new WrongMsgReceivedException(spectedMessageType, message); } return(message); } catch (SerializationException receiveError) { throw new NothingReceivedException(receiveError.InnerException); } }
public WrongMsgReceivedException(int spectedType, Message.BaseMessage gotType) : base(string.Format("Received wrong message: spected {0} but received {1} ({2})", spectedType, gotType, gotType.Type)) { this.spectedType = spectedType; this.receivedMessage = gotType; }
public Result Play() { board.Clear(); playerIndex = -1; Server.Client winner = null; Console.WriteLine("Game::Play(), match starting"); while (winner == null && board.HasAnyEmpty) { playerIndex = NextPlayerIndex; Server.Client currentPlayer = players[playerIndex]; Console.WriteLine("Game::Play(), {0} turn", currentPlayer.symbol.ToString()); Position position; Message.Position positionMsg; try { Message.BaseMessage message = Message.Util.Receive(currentPlayer.client.GetStream(), Message.Position.TypeId); positionMsg = (Message.Position)message; position = new Position(positionMsg.i, positionMsg.j); } catch (Message.NothingReceivedException) { Result errorResult = new Result(); errorResult.type = Result.Type.Error; return(errorResult); } Console.WriteLine("Game::Play(), received position {0}", position); board.Mark(position, currentPlayer.symbol); Server.Client nextPlayer = players[NextPlayerIndex]; bool sentOk = Message.Util.Send(nextPlayer.client.GetStream(), positionMsg); if (!sentOk) { Result errorResult = new Result(); errorResult.type = Result.Type.Error; return(errorResult); } if (board.HasWon(position)) { winner = currentPlayer; } } Result okResult = new Result(); okResult.type = Result.Type.Ok; if (board.HasAnyEmpty) { okResult.winner = winner; } return(okResult); }