private void btnListen_Click(object sender, EventArgs e) { // Parse the server's IP address out of the TextBox IPAddress ipAddr = IPAddress.Parse(txtIp.Text); // Create a new instance of the ChatServer object ChatServer mainServer = new ChatServer(ipAddr); // Hook the StatusChanged event handler to mainServer_StatusChanged ChatServer.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged); // Start listening for connections mainServer.StartListening(); // Show that we started to listen for connections txtLog.AppendText("Chờ người vào phòng ...\r\n"); btnListen.Enabled = false; }
// Occures when a new client is accepted private void AcceptClient() { srReceiver = new System.IO.StreamReader(tcpClient.GetStream()); swSender = new System.IO.StreamWriter(tcpClient.GetStream()); // Read the account information from the client currUser = srReceiver.ReadLine(); // We got a response from the client if (currUser != "") { // Store the user name in the hash table if (ChatServer.htUsers.Contains(currUser) == true) { // 0 means not connected swSender.WriteLine("0|Tên này đã tồn tại!"); swSender.Flush(); CloseConnection(); return; } else if (currUser == "Administrator") { // 0 means not connected swSender.WriteLine("0|This username is reserved."); swSender.Flush(); CloseConnection(); return; } else { // 1 means connected successfully swSender.WriteLine("1"); swSender.Flush(); // Add the user to the hash tables and start listening for messages from him ChatServer.AddUser(tcpClient, currUser); } } else { CloseConnection(); return; } try { // Keep waiting for a message from the user while ((strResponse = srReceiver.ReadLine()) != "") { // If it's invalid, remove the user if (strResponse == null) { ChatServer.RemoveUser(tcpClient); } else { // Otherwise send the message to all the other users ChatServer.SendMessage(currUser, strResponse); } } } catch { // If anything went wrong with this user, disconnect him ChatServer.RemoveUser(tcpClient); } }