Advertisement
toko214

chat server

Jun 22nd, 2016
716
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 18.34 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Threading;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.IO;
  12. using System.Collections;
  13.  
  14. namespace ChatServer
  15. {
  16.     public partial class Form1 : Form
  17.     {
  18.         private delegate void UpdateStatusCallback(string strMessage);
  19.  
  20.         bool connected;
  21.         public static int online = 0;
  22.         // This hash table stores users and connections (browsable by user)
  23.         public static Hashtable htUsers;// 30 users at one time limit
  24.         // This hash table stores connections and users (browsable by connection)
  25.         public static Hashtable htConnections; // 30 users at one time limit
  26.         // Will store the IP address passed to it
  27.         private IPAddress ipAddress;
  28.         private TcpClient tcpClient;
  29.         // The event and its argument will notify the form when a user has connected, disconnected, send message, etc.
  30.         public static event StatusChangedEventHandler StatusChanged;
  31.  
  32.         private static StatusChangedEventArgs e;
  33.         // The thread that will hold the connection listener
  34.         private Thread thrListener;
  35.  
  36.         // The TCP object that listens for connections
  37.         private TcpListener tlsClient;
  38.  
  39.         // Will tell the while loop to keep monitoring for connections
  40.         private bool ServRunning = false;
  41.  
  42.         public Form1()
  43.         {
  44.             InitializeComponent();
  45.             connected = false;
  46.         }
  47.  
  48.         private void btnListen_Click(object sender, EventArgs e)
  49.         {
  50.             if (ServRunning == false)
  51.             {
  52.                 htConnections = new Hashtable(30);
  53.                 htUsers = new Hashtable(30);
  54.                 // Parse the server's IP address out of the TextBox
  55.                 ipAddress = IPAddress.Parse(txtIp.Text);
  56.                 // Create a new instance of the ChatServer object
  57.                 // Hook the StatusChanged event handler to mainServer_StatusChanged
  58.                 StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged);
  59.                 // Start listening for connections
  60.                 StartListening();
  61.                 connected = true;
  62.                 // Show that we started to listen for connections
  63.                 txtLog.AppendText("Monitoring for connections...\r\n");
  64.                 Thread th = new Thread(updateOnline);
  65.                 th.Start();
  66.                 btnListen.Text = "Stop Listening";
  67.             }
  68.             else
  69.             {
  70.                 ServRunning = false;
  71.                 btnListen.Text = "Start Listening";
  72.                 htConnections = null;
  73.                 htUsers = null;
  74.             }
  75.         }
  76.  
  77.         public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
  78.         {
  79.             // Call the method that updates the form
  80.             this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
  81.         }
  82.  
  83.         private void UpdateStatus(string strMessage)
  84.         {
  85.             // Updates the log with the message
  86.             txtLog.AppendText(strMessage + "\r\n");
  87.         }
  88.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  89.         {
  90.             if (ServRunning==false)
  91.             {
  92.                 connected = false;
  93.                 MessageBox.Show("asd");
  94.                 stopServer();
  95.                 Environment.Exit(1);
  96.             }
  97.             else
  98.             {
  99.                 Environment.Exit(1);
  100.             }
  101.            
  102.         }
  103.         public void updateOnline()
  104.         {
  105.             while (ServRunning)
  106.             {
  107.                 label2.Text = getOnline().ToString();
  108.                 string listOfUsers = getList();
  109.                 textBox2.Text = listOfUsers;
  110.                 Thread.Sleep(1000);
  111.             }
  112.         }
  113.         private void button1_Click(object sender, EventArgs e)
  114.         {
  115.             SendAdminMessage(textBox1.Text);
  116.         }
  117.         private void SendAdminMessage(string Message)
  118.         {
  119.             try
  120.             {
  121.                 e = new StatusChangedEventArgs(DateTime.Now.ToString()+":"+DateTime.Now.Millisecond + " Administrator: " + Message);
  122.                 OnStatusChanged(e);
  123.                 //txtLog.AppendText("asd"+ "\r\n");
  124.                 //UpdateStatus(Message);
  125.                 //txtLog.AppendText(DateTime.Now.ToString() + " Administrator: " + Message + "\r\n");
  126.                 StreamWriter swSenderSender;
  127.                 // Create an array of TCP clients, the size of the number of users we have
  128.                 TcpClient[] tcpClients = new TcpClient[htUsers.Count];
  129.                 // Copy the TcpClient objects into the array
  130.                 htUsers.Values.CopyTo(tcpClients, 0);
  131.                 // Loop through the list of TCP clients
  132.                 for (int i = 0; i < tcpClients.Length; i++)
  133.                 {
  134.                     // Try sending a message to each
  135.                     try
  136.                     {
  137.                         // If the message is blank or the connection is null, break out
  138.                         if (Message.Trim() == "" || tcpClients[i] == null)
  139.                         {
  140.                             continue;
  141.                         }
  142.                         // Send the message to the current user in the loop
  143.                         swSenderSender = new StreamWriter(tcpClients[i].GetStream());
  144.                         swSenderSender.WriteLine(DateTime.Now.ToString() + " Administrator: " + Message);
  145.                         swSenderSender.Flush();
  146.                         swSenderSender = null;
  147.                     }
  148.                     catch // If there was a problem, the user is not there anymore, remove him
  149.                     {
  150.                         RemoveUser(tcpClients[i]);
  151.                     }
  152.                 }
  153.             }
  154.             catch
  155.             {
  156.                 MessageBox.Show("asd");
  157.             }
  158.         }
  159.  
  160.         private void AddUser(TcpClient tcpUser, string strUsername)
  161.         {
  162.             // First add the username and associated connection to both hash tables
  163.             htUsers.Add(strUsername, tcpUser);
  164.             htConnections.Add(tcpUser, strUsername);
  165.  
  166.             // Tell of the new connection to all other users and to the server form
  167.             SendAdminMessage(htConnections[tcpUser] + " has joined FROYO");
  168.         }
  169.         public static int getOnlineOnline()
  170.         {
  171.             return online;
  172.         }
  173.  
  174.         // Remove the user from the hash tables
  175.         private void RemoveUser(TcpClient tcpUser)
  176.         {
  177.             // If the user is there
  178.             if (htConnections[tcpUser] != null)
  179.             {
  180.                 // First show the information and tell the other users about the disconnection
  181.                 SendAdminMessage(htConnections[tcpUser] + " has left FROYO");
  182.  
  183.                 // Remove the user from the hash table
  184.                   htUsers.Remove(htConnections[tcpUser]);
  185.                    htConnections.Remove(tcpUser);
  186.             }
  187.         }
  188.         public void stopServer()
  189.         {
  190.             ServRunning = false;
  191.         }
  192.         // This is called when we want to raise the StatusChanged event
  193.         public static void OnStatusChanged(StatusChangedEventArgs e)
  194.         {
  195.             StatusChangedEventHandler statusHandler = StatusChanged;
  196.             if (statusHandler != null)
  197.             {
  198.                 // Invoke the delegate
  199.                 statusHandler(null, e);
  200.             }
  201.         }
  202.        
  203.         public static int getOnline()
  204.         {
  205.             return htUsers.Count;
  206.  
  207.         }
  208.         // Send administrative messages
  209.  
  210.         // Send messages from one user to all the others
  211.         private void SendMessage(string From, string Message)
  212.         {
  213.             StreamWriter swSenderSender;
  214.  
  215.             // First of all, show in our application who says what
  216.             e = new StatusChangedEventArgs(DateTime.Now.ToString() + " " + From + ": " + Message);
  217.             OnStatusChanged(e);
  218.  
  219.             // Create an array of TCP clients, the size of the number of users we have
  220.             TcpClient[] tcpClients = new TcpClient[htUsers.Count];
  221.             // Copy the TcpClient objects into the array
  222.             htUsers.Values.CopyTo(tcpClients, 0);
  223.             int count = 0;
  224.             string[] users = new string[htUsers.Count];
  225.             foreach (object key in htUsers.Keys)
  226.             {
  227.                 users[count] = key.ToString();
  228.                 count++;
  229.             }
  230.             // Loop through the list of TCP clients
  231.             for (int i = 0; i < tcpClients.Length; i++)
  232.             {
  233.                 // Try sending a message to each
  234.                 try
  235.                 {
  236.                     // If the message is blank or the connection is null, break out
  237.                     if (Message.Trim() == "" || tcpClients[i] == null || users[i] == From)
  238.                     {
  239.                         continue;
  240.                     }
  241.                     // Send the message to the current user in the loop
  242.  
  243.                     swSenderSender = new StreamWriter(tcpClients[i].GetStream());
  244.                     swSenderSender.WriteLine(DateTime.Now.ToString() + " " + From + ": " + Message);
  245.                     swSenderSender.Flush();
  246.                     swSenderSender = null;
  247.                 }
  248.                 catch // If there was a problem, the user is not there anymore, remove him
  249.                 {
  250.                     RemoveUser(tcpClients[i]);
  251.                 }
  252.             }
  253.         }
  254.         public void StartListening()
  255.         {
  256.             int port = 1986;
  257.            // Get the IP of the first network device, however this can prove unreliable on certain configurations
  258.             IPAddress ipaLocal = ipAddress;
  259.  
  260.             // Create the TCP listener object using the IP of the server and the specified port
  261.             tlsClient = new TcpListener(ipaLocal,port);
  262.  
  263.             // Start the TCP listener and listen for connections
  264.             tlsClient.Start();
  265.  
  266.             // The while loop will check for true in this before checking for connections
  267.             ServRunning = true;
  268.  
  269.             // Start the new tread that hosts the listener
  270.             thrListener = new Thread(KeepListening);
  271.             thrListener.Start();
  272.            
  273.         }
  274.  
  275.         private void KeepListening()
  276.         {
  277.             // While the server is running
  278.             while (ServRunning == true)
  279.             {
  280.                 // Accept a pending connection
  281.                 tcpClient = tlsClient.AcceptTcpClient();
  282.                 if (tcpClient != null)
  283.                 {
  284.                     Connection newConnection = new Connection(tcpClient);
  285.                     online++;
  286.                 }
  287.                 // Create a new instance of Connection
  288.                 tcpClient = null;
  289.                 Thread.Sleep(100);
  290.             }
  291.             tcpClient = null;
  292.             tlsClient.Stop();
  293.             tlsClient = null;
  294.         }
  295.         public static string getList()
  296.         {
  297.             string users = "";
  298.             foreach (object key in htUsers.Keys)
  299.             {
  300.                 users += key.ToString() + "\r\n";
  301.             }
  302.             return users;
  303.         }
  304.         class Connection
  305.         {
  306.             TcpClient tcpClient;
  307.             // The thread that will send information to the client
  308.             private Thread thrSender;
  309.             private StreamReader srReceiver;
  310.             private StreamWriter swSender;
  311.             private string currUser;
  312.             private string strResponse;
  313.             private string KindOf;
  314.             Form1 sa = new Form1();
  315.             // The constructor of the class takes in a TCP connection
  316.             public Connection(TcpClient tcpCon)
  317.             {
  318.                 tcpClient = tcpCon;
  319.                 // The thread that accepts the client and awaits messages
  320.                 thrSender = new Thread(AcceptClient);
  321.                 // The thread calls the AcceptClient() method
  322.                 thrSender.Start();
  323.  
  324.             }
  325.  
  326.  
  327.             public void SendOnline(string amount)
  328.             {
  329.                 StreamWriter swSenderSender;
  330.  
  331.                 // Create an array of TCP clients, the size of the number of users we have
  332.                 TcpClient[] tcpClients = new TcpClient[htUsers.Count];
  333.                 // Copy the TcpClient objects into the array
  334.                 htUsers.Values.CopyTo(tcpClients, 0);
  335.  
  336.                 // Loop through the list of TCP clients
  337.                 for (int i = 0; i < tcpClients.Length; i++)
  338.                 {
  339.                     // Try sending a message to each
  340.                     try
  341.                     {
  342.                         // If the message is blank or the connection is null, break out
  343.                         if (amount.Trim() == "" || tcpClients[i] == null)
  344.                         {
  345.                             continue;
  346.                         }
  347.                         // Send the message to the current user in the loop
  348.  
  349.                         swSenderSender = new StreamWriter(tcpClients[i].GetStream());
  350.                         swSenderSender.WriteLine(amount);
  351.                         swSenderSender.Flush();
  352.                         swSenderSender = null;
  353.                     }
  354.                     catch // If there was a problem, the user is not there anymore, remove him
  355.                     {
  356.                        sa.RemoveUser(tcpClients[i]);
  357.                     }
  358.                 }
  359.             }
  360.             private void CloseConnection()
  361.             {
  362.                 // Close the currently open objects
  363.                 KindOf = "close";
  364.             }
  365.             // Occures when a new client is accepted
  366.             private void AcceptClient()
  367.             {
  368.                 KindOf = "message";
  369.                 srReceiver = new StreamReader(tcpClient.GetStream());
  370.                 swSender = new StreamWriter(tcpClient.GetStream());
  371.  
  372.                 // Read the account information from the client
  373.                 currUser = srReceiver.ReadLine();
  374.  
  375.                 // We got a response from the client
  376.                 if (currUser != "")
  377.                 {
  378.                     // Store the user name in the hash table
  379.                     if (htUsers.Contains(currUser) == true)
  380.                     {
  381.  
  382.                         // 0 means not connected
  383.                         swSender.WriteLine("0|This username already exists.");
  384.                         swSender.Flush();
  385.                         CloseConnection();
  386.                         return;
  387.                     }
  388.                     else if (currUser == "Administrator")
  389.                     {
  390.                         // 0 means not connected
  391.                         swSender.WriteLine("0|This username is reserved.");
  392.                         swSender.Flush();
  393.                         CloseConnection();
  394.                         return;
  395.                     }
  396.                     else
  397.                     {
  398.                         // 1 means connected successfully
  399.                         swSender.WriteLine("1");
  400.                         swSender.Flush();
  401.  
  402.                         // Add the user to the hash tables and start listening for messages from him
  403.                        sa. AddUser(tcpClient, currUser);
  404.                     }
  405.                 }
  406.                 else
  407.                 {
  408.                     CloseConnection();
  409.                     return;
  410.                 }
  411.                 SendOnline("♥" + getOnline());
  412.                 string users = "";
  413.                 foreach (object key in htUsers.Keys)
  414.                 {
  415.                     users += key.ToString() + "*";
  416.                 }
  417.                 SendOnline("▲" + users);
  418.                 try
  419.                 {
  420.                     strResponse = getMessage();
  421.                     // Keep waiting for a message from the user
  422.                     while (strResponse != "close")
  423.                     {
  424.                         // If it's invalid, remove the user
  425.                         if (strResponse == null)
  426.                         {
  427.                             sa.RemoveUser(tcpClient);
  428.                         }
  429.                         else
  430.                         {
  431.                             // Otherwise send the message to all the other users
  432.                            sa.SendMessage(currUser, strResponse);
  433.                         }
  434.                         strResponse = getMessage();
  435.                         Thread.Sleep(100);
  436.                     }
  437.                     tcpClient.Close();
  438.                     srReceiver.Close();
  439.                     swSender.Close();
  440.                 }
  441.                 catch
  442.                 {
  443.                     // If anything went wrong with this user, disconnect him
  444.                    sa.RemoveUser(tcpClient);
  445.                     SendOnline("♥" + getOnline());
  446.                     string users2 = "";
  447.                     foreach (object key in htUsers.Keys)
  448.                     {
  449.                         users2 += key.ToString() + "*";
  450.                     }
  451.                     SendOnline("▲" + users2);
  452.                 }
  453.             }
  454.             private string getMessage()
  455.             {
  456.                 if (KindOf == "close")
  457.                 {
  458.                     return KindOf;
  459.                 }
  460.                 if (KindOf == "message")
  461.                 {
  462.                     return srReceiver.ReadLine();
  463.                 }
  464.                 return "";
  465.             }
  466.         }
  467.         public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);
  468.         public class StatusChangedEventArgs : EventArgs
  469.         {
  470.             // The argument we're interested in is a message describing the event
  471.             private string EventMsg;
  472.  
  473.             // Property for retrieving and setting the event message
  474.             public string EventMessage
  475.             {
  476.                 get
  477.                 {
  478.                     return EventMsg;
  479.                 }
  480.                 set
  481.                 {
  482.                     EventMsg = value;
  483.                 }
  484.             }
  485.  
  486.             // Constructor for setting the event message
  487.             public StatusChangedEventArgs(string strEventMsg)
  488.             {
  489.                 EventMsg = strEventMsg;
  490.             }
  491.         }
  492.     }
  493. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement