public void Connect() { try { _log = new Log("client", Directories.Logs_Path, logEn); _sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var ar = _sock.BeginConnect(new IPEndPoint(IPAddress.Parse(_ip), ALL.MainPort), null, null); bool result = ar.AsyncWaitHandle.WaitOne(3000); if (result) { _log.WriteLineInfo($"Connected to {_ip} !"); _stream = new SslStream(new NetworkStream(_sock, true), false, (e1, e2, e3, e4) => { return(true); }); _stream.AuthenticateAsClient("localhost"); if (_stream.IsAuthenticated) { _log.WriteLineInfo($"SSL Stream : \r\n{'{'}\r\n\tIsAuthenticated: {_stream.IsAuthenticated.ToString()}\r\n\tIsEncrypted: {_stream.IsEncrypted.ToString()}\r\n{'}'}"); _buffer = new byte[1024]; _stream.BeginRead(_buffer, 0, _buffer.Length, StreamRead, null); ConnectedSuccessfully?.Invoke(this, new EventArgs()); } } else { _log.WriteLineError("Connection failed after 3 seconds !"); } } catch (Exception ex) { _log.WriteLineError(ex); } }
// --- RECEIVING METHODS --- private async Task connect() { connection.On("ReceiveMessage", (string message) => { MainWindow.Instance.Dispatcher.Invoke(() => { Logger.Log("Received message: " + message); }); }); connection.On("AnnounceNewPlayer", (string id, Point position) => { MainWindow.Instance.Dispatcher.Invoke(() => { Logger.Log($"New player joined, Id: {id}"); GameManager.Instance.CreatePlayer(id, position); }); }); connection.On("GetGameState", (string[] ids, Point[] positions) => { MainWindow.Instance.Dispatcher.Invoke(() => { Logger.Log($"Received game state: {ids.Length} other players currently in-game"); for (int i = 0; i < ids.Length; i++) { GameManager.Instance.CreatePlayer(ids[i], positions[i]); } }); }); connection.On("MoveObject", (string id, Point position) => { MainWindow.Instance.Dispatcher.Invoke(() => { Debug.WriteLine($"Move receive. ID: {id}, {position}"); GameManager.Instance.MovePlayer(id, position); }); }); // --- CONNECTING --- try { await connection.StartAsync(); connected = true; Logger.Log("CONNECTION ESTABLISHED to " + SERVER_URL); if (ConnectedSuccessfully != null) { ConnectedSuccessfully.Invoke(); } } catch (Exception ex) { connected = false; Debug.WriteLine($"CONNECTION FAILED: {ex.Message}"); } }