static void ClientListener(ref ListenerState state) { TcpListener server = new TcpListener(iPAddress, DesktopPort); server.Start(); while (true) { state = ListenerState.Waiting; TcpClient client = server.AcceptTcpClient(); NetworkStream stream = client.GetStream(); //SslStream ssl = new SslStream(client.GetStream(), false); //ssl.AuthenticateAsServer(X509, false, true); state = ListenerState.UsernameSub; while (client.Available < 3) { if (state == ListenerState.Quiting) { break; } } if (state == ListenerState.Quiting) { server.Stop(); break; } Message message = MessageHelpers.GetMessage(stream); if (message.MessageType == MessageType.Initionalize && clients.Any(x => x.Value.Name == message.Name) == false) { ClientInfo c = new ClientInfo(message.Name, stream, ClientType.Desktop); clients.Add(c.GUID, c); ThreadPool.QueueUserWorkItem(HandleClientDesktopWorker, c); state = ListenerState.Connected; } else { state = ListenerState.Disconnected; Message h = new Message(message.Name, MessageType.Status); h.SetStatusType(StatusType.ErrorDisconnect); h.SetContent("User with the name " + message.Name + " already exists"); MessageHelpers.SetMessage(stream, h); stream.Close(); stream.Dispose(); client.Close(); client.Dispose(); } } }
static void TestThread(object d) { TcpClient client = new TcpClient("novastudios.tk", 8910); Message secure = MessageHelpers.GetMessage(client.GetStream()); User user = null; if (secure.Content != "") { SslStream ssl = new SslStream(client.GetStream(), false); ssl.AuthenticateAsClient(secure.Content); user = new User(Guid.NewGuid().ToString(), ssl); user.Init(); } else { user = new User(Guid.NewGuid().ToString(), client.GetStream()); user.Init(); } user.OnMessageStatusReceivedCallback += (message) => { if (message.StatusType == StatusType.ErrorDisconnect) { Console.WriteLine(user.Name + " Error: " + message.Content); } }; Random rnd = new Random(); Console.WriteLine("Worker Running"); while (!cts.IsCancellationRequested) { user.CreateMessage(RandomString(rnd, 20), NColor.GenerateRandomColor()); Thread.Sleep(rnd.Next(750, 1000)); } user.CreateStatus(StatusType.Disconnecting); try { user.Close(); } catch { } Console.WriteLine("Worker Quit"); }
private static void HandleClientDesktopWorker(object token) { ClientInfo c = (ClientInfo)token; NetworkStream stream = c.Stream; // Let bots know there is a new user foreach (dynamic b in Bots) { b.OnUserConnect(c); } // Tell all connected clients that we are connected Message cm = new Message(c.Name, MessageType.Status); cm.SetStatusType(StatusType.Connected); SendToAllClients(cm, null, -1); Room r = new Room(); // Put user in none full room foreach (KeyValuePair <string, Room> room in Rooms) { if (!room.Value.AddUser(c)) { continue; } else { r = room.Value; break; } } if (r.Equals(default(Room))) { JsonMessage m = new JsonMessage("Server", MessageType.Status); m.SetStatusType(StatusType.ErrorDisconnect); m.SetContent("All available rooms are full"); JsonMessageHelpers.SetJsonMessage(stream, m); return; } Message rooms = new Message("Server", MessageType.Request); rooms.SetRequestType(RequestType.Rooms); rooms.SetContent(Rooms.SerializeRooms()); MessageHelpers.SetMessage(stream, rooms); // Send The Server Message Buffer foreach (Message message in r.Buffer) { MessageHelpers.SetMessage(stream, message); } while (true) { try { c = clients[c.GUID]; Message m = MessageHelpers.GetMessage(stream); foreach (dynamic b in Bots) { m = b.OnMessage(c, m); } // Manage Message buffer if (m.MessageType == MessageType.Message) { r.AddMesssage(m); } else if (m.MessageType == MessageType.Infomation) { MessageHelpers.SetMessage(stream, InformationHandler(m.InfomationType, c.GUID)); continue; } else if (m.MessageType == MessageType.Status && m.StatusType == StatusType.ChangeRoom) { try { ClientInfo cInfo = clients[c.GUID]; if (!r.AddUser(cInfo)) { m = new Message("Server", MessageType.Message); m.SetColor(ColorToNColor(Color.Aquamarine)); m.SetContent("The requested room is full"); MessageHelpers.SetMessage(stream, m); continue; } r.RemoveUser(cInfo); int id = int.Parse(m.Content); cInfo.SetRoomID(id); clients[c.GUID] = cInfo; Room oldR = r; r = Rooms.Where(x => x.Value.ID == id).First().Value; r.AddUser(cInfo); m = new Message("Server", MessageType.Message); m.SetContent("Moved to Room " + r.Name + "(" + id + ")"); MessageHelpers.SetMessage(stream, m); foreach (Message message in r.Buffer) { MessageHelpers.SetMessage(stream, message); } foreach (dynamic b in Bots) { b.OnUserChangeRoom(c, oldR, r); } continue; } catch { try { ClientInfo cInfo = clients[c.GUID]; Room oldR = r; r = Rooms.Where(x => x.Value.Name == m.Content).First().Value; cInfo.SetRoomID(r.ID); r.AddUser(cInfo); clients[c.GUID] = cInfo; m = new Message("Server", MessageType.Message); m.SetContent("Moved to Room " + r.Name); MessageHelpers.SetMessage(stream, m); foreach (Message message in r.Buffer) { MessageHelpers.SetMessage(stream, message); } foreach (dynamic b in Bots) { b.OnUserChangeRoom(c, oldR, r); } continue; } catch { continue; } } } if (m.Name != c.Name) { m.SetName(c.Name); } if (m.StatusType == StatusType.Disconnecting && m.MessageType == MessageType.Status) { foreach (dynamic b in Bots) { b.OnUserDisconnect(c); } r.RemoveUser(clients[c.GUID]); MessageHelpers.SetMessage(stream, m); stream.Close(); clients.Remove(c.GUID); Message d = new Message(c.Name, MessageType.Status); d.SetStatusType(StatusType.Disconnected); SendToAllClients(d, null, -1); break; } foreach (KeyValuePair <string, ClientInfo> network in clients) { if (network.Key == c.GUID) { continue; } else { if (m.EndPoint == "") { SendToAllClients(m, null, clients[c.GUID].RoomId, c.GUID); break; } else { if (network.Value.Name == m.EndPoint) { MessageHelpers.SetMessage(network.Value.Stream, m); } } } } } catch (IOException) { if (clients.ContainsKey(c.GUID)) { foreach (dynamic b in Bots) { b.OnUserDisconnect(c); } r.RemoveUser(clients[c.GUID]); clients[c.GUID].Stream.Close(); clients.Remove(c.GUID); } foreach (KeyValuePair <string, ClientInfo> network in clients) { Message d = new Message(network.Key == c.Name ? "You" : c.Name, MessageType.Status); d.SetStatusType(StatusType.Disconnected); MessageHelpers.SetMessage(network.Value.Stream, d); } break; } catch (Exception ex) { if (clients.ContainsKey(c.GUID)) { foreach (dynamic b in Bots) { b.OnUserDisconnect(c); } r.RemoveUser(clients[c.GUID]); clients[c.GUID].Stream.Close(); clients.Remove(c.GUID); } Console.WriteLine(c.Name + " disconnected due to an error. Details: " + ex.Message); foreach (KeyValuePair <string, ClientInfo> network in clients) { Message e = new Message(network.Key == c.Name ? "You" : c.Name, MessageType.Status); e.SetStatusType(StatusType.ErrorDisconnect); MessageHelpers.SetMessage(network.Value.Stream, e); } break; } } }
public ChatUI() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Enabled; Color = NColor.GenerateRandomColor(); Window.Current.Closed += (s, e) => { if (user != null) { user.CreateStatus(StatusType.Disconnecting); } }; Loaded += async(s, e) => { if (!connected) { client = new TcpClient(); await client.ConnectAsync(Address, Port); NetworkStream stream = client.GetStream(); Message secure = MessageHelpers.GetMessage(stream); string password = ""; if (secure.Name == "locked") { PasswordDialog pd = new PasswordDialog(); if (await pd.ShowAsync() == ContentDialogResult.Primary) { password = pd.Password; } else { if (Frame.CanGoBack) { Frame.GoBack(); } } } if (secure.Content != "") { SslStream ssl = new SslStream(stream); ssl.AuthenticateAsClient(secure.Content); user = new User(Username, ssl); user.Init(password); } else { user = new User(Username, stream); user.Init(password); } user.OnMessageReceivedCallback += User_OnMessageReceivedCallback; user.OnMessageStatusReceivedCallback += User_OnMessageStatusReceivedCallback; user.OnMessageTransferReceivedCallback += User_OnMessageTransferReceivedCallback; user.OnMessageWhisperReceivedCallback += User_OnMessageWhisperReceivedCallback; user.OnMessageInitReceivedCallback += User_OnMessageInitReceivedCallback; user.OnMesssageInformationReceivedCallback += User_OnMesssageInformationReceivedCallback; user.OnErrorCallback += (d) => { Debug.WriteLine(d.Message); }; connected = true; } }; }
private void Connect() { if (IPBox.Text == "IP Address" || IPBox.Text.Length < 1) { if (debug) { IPBox.Text = GetLocalIPAddress(); } else { IPBox.Text = "novastudios.tk"; } } Thread t = new Thread(delegate() { try { if (tcpClient != null) { if (tcpClient.Connected) { user.CreateStatus(StatusType.Disconnecting); ChangeConnectionInputState(true); //FixClient(); return; } } print("Connecting... ", Log); tcpClient = new TcpClient(IPBox.Text, 8910); ChatLib.Message secure = MessageHelpers.GetMessage(tcpClient.GetStream()); string password = ""; if (secure.Name == "locked") { using (TextInput input = new TextInput()) { if (input.ShowDialog() == DialogResult.OK) { password = input.Password; } else { user.CreateStatus(StatusType.Disconnecting); ChangeConnectionInputState(true); return; } } } if (secure.Content != "") { SslStream ssl = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); ssl.AuthenticateAsClient(secure.Content); user = new User(nameBox.Text, ssl); user.Init(password); } else { user = new User(nameBox.Text, tcpClient.GetStream()); user.Init(password); } // Setup Callbacks user.OnMessageReceivedCallback += User_OnMessageReceivedCallback; user.OnMessageStatusReceivedCallback += User_OnMessageStatusReceivedCallback; user.OnMessageTransferReceivedCallback += User_OnMessageTransferReceivedCallback; user.OnMessageWhisperReceivedCallback += User_OnMessageWhisperReceivedCallback; user.OnMessageInitReceivedCallback += User_OnMessageInitReceivedCallback; //user.OnMessageAnyReceivedCallback += User_OnMessageAnyReceivedCallback; user.OnMessageRequestReceivedCallback += User_OnMessageRequestReceivedCallback; user.OnMesssageInformationReceivedCallback += User_OnMesssageInformationReceivedCallback; user.OnErrorCallback += (e) => { print(e.Message + " " + e.TargetSite + " " + GetLineNumber(e), Log); }; ChangeConnectionInputState(false); print("Successfully connected to " + IPBox.Text, Log, Color.LimeGreen); } catch (Exception ex) { print("Connection failed -> " + ex.Message, Log, Color.Red); } }); t.IsBackground = true; t.Start(); }
private void Listen(object stream) { try { if (IsSecure) { while (Active) { SslStream nStream = (SslStream)stream; Message m = MessageHelpers.GetMessage(nStream); switch (m.MessageType) { case MessageType.Message: OnMessageReceivedCallback?.Invoke(m); break; case MessageType.Status: OnMessageStatusReceivedCallback?.Invoke(m); break; case MessageType.Transfer: OnMessageTransferReceivedCallback?.Invoke(m); break; case MessageType.Whisper: OnMessageWhisperReceivedCallback?.Invoke(m); break; case MessageType.Initialize: OnMessageInitReceivedCallback?.Invoke(m); break; case MessageType.Request: OnMessageRequestReceivedCallback?.Invoke(m); break; case MessageType.Infomation: OnMesssageInformationReceivedCallback?.Invoke(m); break; } OnMessageAnyReceivedCallback?.Invoke(m); } } else { NetworkStream nStream = (NetworkStream)stream; while (Active) { Message m = MessageHelpers.GetMessage(nStream); switch (m.MessageType) { case MessageType.Message: OnMessageReceivedCallback?.Invoke(m); break; case MessageType.Status: OnMessageStatusReceivedCallback?.Invoke(m); break; case MessageType.Transfer: OnMessageTransferReceivedCallback?.Invoke(m); break; case MessageType.Whisper: OnMessageWhisperReceivedCallback?.Invoke(m); break; case MessageType.Initialize: OnMessageInitReceivedCallback?.Invoke(m); break; case MessageType.Request: OnMessageRequestReceivedCallback?.Invoke(m); break; case MessageType.Infomation: OnMesssageInformationReceivedCallback?.Invoke(m); break; } OnMessageAnyReceivedCallback?.Invoke(m); } } } catch (Exception e) { OnErrorCallback?.Invoke(e); } }