public Communicator(Settings settings, Battlefield battlefield, GameStateClient gameState, out RealCharacter player) { _battlefield = battlefield; _gameState = gameState; // подключаемся к серверу ServerConnectionPacket connMsg = Connect(settings, ref _clientPort); if (connMsg == null) { _battlefield.Game.Exit(); } _messenger = new UdpMessenger(settings.ServerAddress, settings.ServerPort, _clientPort, _receiveTimeout); _gameState.SetLevel((Level)connMsg.Level); // обновление состояния игрока _gameState.CreateCharacter(connMsg.PlayerId); player = _gameState.Players[connMsg.PlayerId]; player.Position = (Vector2)connMsg.PlayerPosition; player.Health = connMsg.Health; player.Speed = connMsg.Speed; player.MoveBehavior = new PlayerMove1(player); _gameState.Player = player; _gameState.NetPlayer = new NetPlayer(_messenger, player); new Thread(StartReceiving).Start(); new Thread(StartSending).Start(); }
private static Settings LoadSettings(string file) { var settings = new Settings(); settings.ServerPort = -1; settings.ServerConnectionPort = -1; using (StreamReader sr = new StreamReader(file)) { string line; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("[Server]")) { settings.ServerAddress = line.Split('"')[1]; } else if (line.StartsWith("[ServerPort]")) { settings.ServerPort = int.Parse(line.Split('"')[1]); } else if (line.StartsWith("[ServerConnectionPort]")) { settings.ServerConnectionPort = int.Parse(line.Split('"')[1]); } } } if (settings.ServerAddress == null || settings.ServerConnectionPort == -1 || settings.ServerPort == -1) { throw new Exception("В Settings.txt отсутствуют все необходимые данные о сервере."); } return settings; }
private ServerConnectionPacket Connect(Settings settings, ref int port) { ServerConnectionPacket connAnswer = null; ProtoMessenger<ConnectionMessage> connMessenger = null; for (int j = 0; j < 20; j++) { try { connMessenger = new ProtoMessenger<ConnectionMessage>(new UdpMessenger(settings.ServerAddress, settings.ServerConnectionPort, port)); break; } catch { port++; } } if (connMessenger == null) { Trace.WriteLine("Failed to connect."); } else { ConnectionMessage connMsg = new ConnectionMessage(port); for (int i = 0; i < 10; i++) { connMessenger.Send(connMsg); try { connAnswer = (ServerConnectionPacket)connMessenger.Receive<ServerConnectionPacket>(); break; } catch { // временно _battlefield.PacketLength = -1; } } connMessenger.Close(); if (connAnswer != null) { Trace.WriteLine("Connection succesful."); } else { Trace.WriteLine("Failed to connect."); } } return connAnswer; }
public Battlefield(Game1 game, Settings settings, GameStateClient gameState) : base(game) { _settings = settings; _gameState = gameState; }