/// <summary> /// When connected, sends broadcast message /// of this clients' username and starts listening for messages /// </summary> private async Task OnConnected() { _ = Task.Run(() => AcceptChatConnections()); await userInfoBroadcaster.SendAsync( Encoding.ASCII.GetBytes(PtpChatCommands.ClientNeedsConnection + " " + clientName), (PtpChatCommands.ClientNeedsConnection + " " + clientName).Length, DefaultOnConnectedEndpoint); OnLocalEventHappened?.Invoke(this, new LogEventArgs() { message = "Sent \"OnConnected\" broadcast message ." }); }
/// <summary> /// Opens tcp connection on <see cref="connectedUserEntries"/>[userEntryIndex] /// if it's opened, returns /// </summary> /// <param name="userEntryIndex"></param> /// <returns></returns> private async Task InitiateTcpConnection(int userEntryIndex) { //Check if user's tcpConnection is open, if not, open it if (connectedUserEntries[userEntryIndex].chatConnection != null && connectedUserEntries[userEntryIndex].chatConnection.Connected) { return; } var newConnection = new TcpClient(); newConnection.Connect(new IPEndPoint(connectedUserEntries[userEntryIndex].ipAddress, DefaultValues.TcpMessagingPort)); connectedUserEntries[userEntryIndex].chatConnection = newConnection; _ = Task.Run(() => messagesTracer.TraceConnectionMessages( newConnection, connectedUserEntries[userEntryIndex].username, newConnection.Client.GetRemoteEndPointIpAddress() == newConnection.Client.GetLocalEndPointIpAddress())); OnLocalEventHappened.Invoke(this, new LogEventArgs() { message = $"Connected to {connectedUserEntries[userEntryIndex].username} ." }); //send who we are to the user, //add "header" to distinguish between usual OnConnected messages. var userInfoBytes = Encoding.ASCII.GetBytes(PtpChatCommands.UserIdentification + " " + clientName); await userInfoBroadcaster.SendAsync( userInfoBytes, userInfoBytes.Length, DefaultOnConnectedEndpoint); }