Advertisement
Guest User

Untitled

a guest
Oct 15th, 2010
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.16 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.IO;
  8. using System.Threading;
  9. using System.Collections;
  10. using System.Windows.Forms;
  11.  
  12.  
  13. namespace ChatServer
  14. {
  15.  
  16.  
  17.  
  18.     public class StatusChangedEventArgs : EventArgs
  19.     {
  20.         //The arguement that we are interested in is a message describing the event
  21.         private string EventMsg;
  22.  
  23.         //Property for retreiving and setting the event message
  24.         public string EventMessage
  25.         {
  26.             get
  27.             {
  28.                 return EventMsg;
  29.             }
  30.             set
  31.             {
  32.                 EventMsg = value;
  33.             }
  34.         }
  35.  
  36.         //Constructor for setting the Event Message
  37.         public StatusChangedEventArgs(string strEventMsg)
  38.         {
  39.             EventMsg = strEventMsg;
  40.         }
  41.  
  42.     }
  43.  
  44.     //This delegate is neede to specify the parameters we're passing to our event
  45.     public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);
  46.  
  47.     class ChatServer
  48.     {
  49.  
  50.         //This hashtable stores users and connections (browsable by user)
  51.         public static Hashtable htUsers = new Hashtable(30); // 30 users at one time limit
  52.        
  53.         //This hashtable stores connections and users (browsable by connection)
  54.         public static Hashtable htConnections = new Hashtable(30); // 30 users at one time limit
  55.  
  56.         //This hashtable stores users status (Ready/Not Ready)
  57.         public static Hashtable htReady = new Hashtable(30); // 30 Users at one time limit
  58.  
  59.         // Will store the IP addresses passed to it
  60.         private IPAddress ipAddress;
  61.  
  62.         private TcpClient tcpClient;
  63.  
  64.         //private String readyStatus;
  65.  
  66.         // The event and it's arguement will notify the form when a user has connected, disconnected, sent a message, etc
  67.  
  68.         public static event StatusChangedEventHandler StatusChanged;
  69.         private static StatusChangedEventArgs e;
  70.  
  71.         // The constructor sets the IP address to the one retreived by the instantiating object
  72.         public ChatServer(IPAddress address)
  73.         {
  74.             ipAddress = address;
  75.         }
  76.  
  77.         // The thread that will hold the connection listener
  78.         private Thread thrListener;
  79.  
  80.         // The TCP object that listens for connections
  81.         private TcpListener tlsClient;
  82.  
  83.         //Will tell the while loop to keep monitoring for conenctions
  84.         bool servRunning = false;
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94.         //Add the user to the hash tables
  95.         public static void AddUser(TcpClient tcpUser, string strUsername, string strUserStatus)
  96.         {
  97.             // First add the username and associated connection to both hash tables
  98.             ChatServer.htUsers.Add(strUsername, tcpUser);
  99.             ChatServer.htConnections.Add(tcpUser, strUsername);
  100.             ChatServer.htReady.Add(strUsername, strUserStatus);
  101.  
  102.             //Tell of the new connection to all other users and to the server form
  103.             SendAdminMessage(htConnections[tcpUser] + " has connected, they are " + strUserStatus);
  104.             Form1 frm = (Form1)Application.OpenForms["Form1"];
  105.             frm.UpdateUsersList();
  106.             frm.UpdateStatusList();
  107.            
  108.         }
  109.  
  110.  
  111.  
  112.         //Remove the user form the hash tables
  113.         public static void RemoveUser(TcpClient tcpUser)
  114.         {
  115.             //If the user is there
  116.             if (htConnections[tcpUser] != null)
  117.             {
  118.                 //First show the information and tell others about the disconnection
  119.                 SendAdminMessage(htConnections[tcpUser] + " has disconnected.");
  120.            
  121.                 //Remove user from the hash tables
  122.                 ChatServer.htUsers.Remove(ChatServer.htConnections[tcpUser]);
  123.                 ChatServer.htConnections.Remove(tcpUser);
  124.                 // ChatServer.htReady.Remove(ChatServer.htConnections[tcpUser]);                             //  -   -   -   -   -   -   -   -   - TRY AND REMOVE USER STATUS FROM HASHTABLE -   -   -   -   -   -   -   -   - //
  125.                 Form1 frm = (Form1)Application.OpenForms["Form1"];
  126.                 frm.UpdateUsersList();
  127.                 frm.UpdateStatusList();
  128.  
  129.                 if (htUsers.Count == 0)
  130.                 {
  131.                     frm.ClearStatus();
  132.                     frm.ClearUsers();
  133.                 }
  134.             }
  135.         }
  136.  
  137.  
  138.  
  139.  
  140.  
  141.  
  142.  
  143.  
  144.  
  145.  
  146.         // This is called when we want to raise the StatusChanged event
  147.         public static void OnStatusChanged(StatusChangedEventArgs e)
  148.         {
  149.             StatusChangedEventHandler statusHandler = StatusChanged;
  150.             if (statusHandler != null)
  151.             {
  152.                 //Invoke the delegate
  153.                 statusHandler(null, e);
  154.             }
  155.         }
  156.  
  157.         //Send Admin message
  158.         public static void SendAdminMessage(string Message)
  159.         {
  160.             StreamWriter swSenderSender;
  161.            
  162.             //Show who says what
  163.             e = new StatusChangedEventArgs(Message);
  164.             OnStatusChanged(e);
  165.  
  166.             //Create an array of TCP clients, the size of the number of users we have
  167.             TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];
  168.             //Copy the TCP objects into the array
  169.             ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
  170.             //Loop through the list of clients
  171.             for (int i = 0; i < tcpClients.Length; i++)
  172.             {
  173.                 //Try sending a message to each
  174.                 try
  175.                 {
  176.                     //if the message is blank or the connection is null, break out
  177.                     if (Message.Trim() == "" || tcpClients[i] == null)
  178.                     {
  179.                         continue;
  180.                     }
  181.                     //Else, send the message to all users in the loop
  182.                     swSenderSender = new StreamWriter(tcpClients[i].GetStream());
  183.                     swSenderSender.WriteLine("Administrator: " + Message);
  184.                     swSenderSender.Flush();
  185.                     swSenderSender = null;
  186.                 }
  187.  
  188.                 catch // If there was a problem, like the user is not there anymore, remove him
  189.                 {
  190.                     RemoveUser(tcpClients[i]);
  191.                 }
  192.             }
  193.  
  194.  
  195.         }
  196.  
  197.         public static void SendMessage(string From, string Message)
  198.         {
  199.             StreamWriter swSenderSender;
  200.  
  201.             //First of all, show our application who says what
  202.             e = new StatusChangedEventArgs(From + ": " + Message);
  203.             OnStatusChanged(e);
  204.  
  205.             //Create an array of TCP Clients, the size of the number of users we have
  206.             TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];
  207.             //Copy the TCP client objects into the array
  208.             ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
  209.            
  210.             //Loop throught the list of tcp clients
  211.             for (int i = 0; i < tcpClients.Length; i++)
  212.             {
  213.                 try
  214.                 {
  215.                     //If the message is blank or the connection is null, break out
  216.                     if (Message.Trim() == "" || tcpClients[i] == null)
  217.                     {
  218.                         continue;
  219.                     }
  220.  
  221.                     //Send the message to the current user in the loop
  222.                     swSenderSender = new StreamWriter(tcpClients[i].GetStream());
  223.                     swSenderSender.WriteLine(From + ": " + Message);
  224.                     swSenderSender.Flush();
  225.                     swSenderSender = null;
  226.                 }
  227.  
  228.                 catch // If there was a problem such as the user not being there any more, remove him.
  229.                 {
  230.                     RemoveUser(tcpClients[i]);
  231.                 }
  232.             }
  233.         }
  234.  
  235.         public void StartListening()
  236.         {
  237.             //Get the IP of the first network device
  238.             IPAddress ipaLocal = ipAddress;
  239.            
  240.             //Create the TCP listener object using the IP of the server and the specified port
  241.             tlsClient = new TcpListener(1986);
  242.  
  243.             //Start the TCP listener and listen for connections
  244.             tlsClient.Start();
  245.  
  246.             //The while loop will check for true in this before checking for connections
  247.             servRunning = true;
  248.  
  249.             //Start the new thread that hosts the listener
  250.             thrListener = new Thread(KeepListening);
  251.             thrListener.Start();
  252.         }
  253.  
  254.         private void KeepListening()
  255.         {
  256.             //While the server is running
  257.             while (servRunning == true)
  258.             {
  259.                 //Accept a pending connection
  260.                 tcpClient = tlsClient.AcceptTcpClient();
  261.  
  262.                 // Create a new intance of Connection
  263.                 Connection newConnection = new Connection(tcpClient);
  264.             }
  265.         }
  266.  
  267.     }
  268.  
  269.     // This class handles connections; there will be as many instances of this as there are clients connected to our server
  270.  
  271.     class Connection
  272.     {
  273.         TcpClient tcpClient;
  274.  
  275.         //The thread that will send information to the client
  276.         private Thread thrSender;
  277.         private StreamReader srReceiver;
  278.         private StreamWriter swSender;
  279.         // --------------------------------------------------- vv New
  280.  //       private StreamReader statReceiver;
  281.  //       private StreamWriter statSender;
  282.         // --------------------------------------------------- ^^ New
  283.         private string currUser;
  284.         private string strResponse;
  285.         private string userStatus = "TEST";
  286.  
  287.         // The constructor of the class takes in a TCP connection
  288.  
  289.         public Connection(TcpClient tcpCon)
  290.         {
  291.             tcpClient = tcpCon;
  292.             // The thread that accepts the client and awaits messages
  293.             thrSender = new Thread(AcceptClient);
  294.             // The thread calls the AcceptClient() method
  295.             thrSender.Start();
  296.         }
  297.  
  298.         private void CloseConnection()
  299.         {
  300.             //Close the currently open objects
  301.             tcpClient.Close();
  302.             srReceiver.Close();
  303.             swSender.Close();
  304.         }
  305.  
  306.  
  307.  
  308.         //Occours when a new client is accepted
  309.         private void AcceptClient()
  310.         {
  311.             srReceiver = new System.IO.StreamReader(tcpClient.GetStream());
  312.             swSender = new System.IO.StreamWriter(tcpClient.GetStream());
  313.  
  314.  //           statReceiver = new System.IO.StreamReader(tcpStatusClient.GetStream());
  315. //            statSender = new System.IO.StreamWriter(tcpStatusClient.GetStream());
  316.            
  317.             //Read the account information from the client
  318.             currUser = srReceiver.ReadLine();
  319.             //userStatus = currUser;                                                             //--------------    -   -   -   -   -   -   -   -   -   Here we set what userStatus is.
  320.             userStatus = srReceiver.ReadLine();
  321.             //We got a response from the client
  322.             if (currUser != "")
  323.             {
  324.                 //Store the users name in a hash table
  325.                 if (ChatServer.htUsers.Contains(currUser) == true)
  326.                 {
  327.                     // 0 means not connected
  328.                     swSender.WriteLine("0|This username already exists.");
  329.                     swSender.Flush();
  330.                     CloseConnection();
  331.                     return;
  332.                 }
  333.  
  334.                 else if (currUser == "Administrator")
  335.                 {
  336.                     swSender.WriteLine("0|This username is reserved");
  337.                     swSender.Flush();
  338.                     CloseConnection();
  339.                     return;
  340.                 }
  341.                 else
  342.                 {
  343.                     // 1 means conencted successfully
  344.                     swSender.WriteLine("1");
  345.                     swSender.Flush();
  346.  
  347.                     // Add the user to the hash tables and start listening to connections from them
  348.  
  349.  
  350.                     ChatServer.AddUser(tcpClient, currUser, userStatus);                                    // -------------    -   -   -   -   --      -   -   - HERE IS WHERE WE FEDINE THE VALUES
  351.                 }
  352.             }
  353.             else
  354.             {
  355.                 CloseConnection();
  356.                 return;
  357.             }
  358.             try
  359.             {
  360.                 //Keep waiting for a message from the user
  361.                 while ((strResponse = srReceiver.ReadLine()) != "")
  362.                 {
  363.                     //If it's invalid, remove the user
  364.                     if (strResponse == null)
  365.                     {
  366.                         ChatServer.RemoveUser(tcpClient);
  367.                     }
  368.                     else
  369.                     {
  370.                         //Otherwise, send the message to all other users
  371.                         ChatServer.SendMessage(currUser, strResponse);
  372.                     }
  373.                 }
  374.             }
  375.             catch
  376.             {
  377.                 //If anything went wrong with this user, disconnect them
  378.                 ChatServer.RemoveUser(tcpClient);
  379.             }
  380.         }
  381.  
  382.     }
  383.  
  384. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement