Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Release [C#] Chat server
#1
I got bored and felt like making something so I tried to make a basic chat server which worked out pretty well after fixing 2 or 3 problems Smile

You can basicly chat with everyone in the server, the server can also say stuff to everyone if you type "say [stuff]"

Just posting this incase anyone is interested in the source code

Server source:
CSHARP Code
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. using System.IO;
  7.  
  8. namespace BasicServer
  9. {
  10. class Program
  11. {
  12. static TcpListener Listener;
  13. static List<Client> Clients = new List<Client>();
  14. static int Port = -1, MaxClients = -1, Connected = 0;
  15. static void Main( string[] args )
  16. {
  17. Console.ForegroundColor = ConsoleColor.White;
  18.  
  19. for( int i = 0 ; i < args.Length ; i++ )
  20. {
  21. if( args[i].ToLower() == "+port" )
  22. {
  23. Port = Convert.ToInt32( args[i + 1] );
  24. i++;
  25. continue;
  26. }
  27.  
  28. if( args[i].ToLower() == "+maxclients" )
  29. {
  30. MaxClients = Convert.ToInt32( args[i + 1] );
  31. i++;
  32. continue;
  33. }
  34. }
  35.  
  36. while( MaxClients < 1 )
  37. {
  38. Console.Write( "Enter the maximum amount of clients(1 or more): " );
  39. MaxClients = Convert.ToInt32( Console.ReadLine() );
  40. }
  41.  
  42. if( Port == -1 )
  43. {
  44. Console.Write( "Please enter the port that you want to use: " );
  45. Port = Convert.ToInt32( Console.ReadLine() );
  46. }
  47.  
  48. Console.Write( "Trying to start the server at port " + Port + ": " );
  49.  
  50. try
  51. {
  52. Listener = new TcpListener( System.Net.IPAddress.Any, Port );
  53. Listener.Start();
  54.  
  55. new Thread( () =>
  56. {
  57. while( true )
  58. {
  59. TcpClient Client = Listener.AcceptTcpClient();
  60. Thread ClientThread = new Thread( new ParameterizedThreadStart( ClientMain ) );
  61. ClientThread.Start( Client );
  62. Connected++;
  63. }
  64. } ).Start();
  65.  
  66. new Thread( new ThreadStart( ReadConsole ) ).Start();
  67.  
  68. Console.ForegroundColor = ConsoleColor.Green;
  69. Console.WriteLine( "Success!" );
  70. Console.ForegroundColor = ConsoleColor.White;
  71. }
  72. catch( Exception e )
  73. {
  74. Console.ForegroundColor = ConsoleColor.Red;
  75. Console.WriteLine( "Failed!" );
  76. Console.WriteLine( "Error: " + e.Message );
  77. Console.ForegroundColor = ConsoleColor.White;
  78. Console.Write( "Press any key to exit..." );
  79. Console.ReadKey();
  80. Environment.Exit( 0 );
  81. }
  82.  
  83. System.Diagnostics.Process.GetCurrentProcess().WaitForExit();
  84. }
  85.  
  86. static void SendToClient( NetworkStream Client, string Text )
  87. {
  88. byte[] buffer = Encoding.ASCII.GetBytes( Text );
  89. Client.Write( buffer, 0, buffer.Length );
  90. Client.Flush();
  91. }
  92.  
  93. static void ReadConsole()
  94. {
  95. string Text;
  96. while( true )
  97. {
  98. Text = Console.ReadLine();
  99.  
  100. if( Text == "quit" )
  101. {
  102. foreach( Client c in Clients )
  103. {
  104. c.Stream.Dispose();
  105. c.Stream.Close();
  106. }
  107. Environment.Exit( 0 );
  108. }
  109.  
  110. if( Text.Split( ' ' )[0].ToLower() == "say" )
  111. {
  112. if( Connected <= 0 )
  113. {
  114. Console.WriteLine( "No clients connected ... " );
  115. continue;
  116. }
  117.  
  118. try
  119. {
  120. foreach( Client c in Clients )
  121. SendToClient(
  122. c.Stream,
  123. "Server: " + Text.Substring( 4 )
  124. );
  125.  
  126. Console.ForegroundColor = ConsoleColor.Cyan;
  127. Console.Write( "Send: \t\t" );
  128. Console.ForegroundColor = ConsoleColor.White;
  129. Console.WriteLine( Text.Substring( 4 ) );
  130. }
  131. catch( Exception e ) { Console.WriteLine( e.Message ); }
  132. }
  133. }
  134. }
  135.  
  136. static void ClientMain( object obj )
  137. {
  138. TcpClient NewClient = ( TcpClient )obj;
  139. NetworkStream ClientStream = NewClient.GetStream();
  140.  
  141. int ID = Connected;
  142. byte[] bMessage = new byte[1024];
  143. string Message;
  144. int Recieved = ClientStream.Read( bMessage, 0, bMessage.Length );
  145. Array.Resize( ref bMessage, Recieved );
  146.  
  147. if( !Encoding.ASCII.GetString( bMessage ).StartsWith( "#info" ) )
  148. {
  149. Console.WriteLine( "Someone tried to connect but it failed!" );
  150. ClientStream.Dispose();
  151. ClientStream.Close();
  152. return;
  153. }
  154.  
  155. string Name = Encoding.ASCII.GetString( bMessage );
  156. Client Client = new Client( Name.Substring( 6 ), ID, ClientStream );
  157. Clients.Add( Client );
  158. Console.WriteLine( "New connection: " + Client.Name );
  159.  
  160. while( true )
  161. {
  162. Recieved = 0;
  163. bMessage = new byte[1024];
  164. try
  165. {
  166. Recieved = ClientStream.Read( bMessage, 0, bMessage.Length );
  167. Array.Resize( ref bMessage, Recieved );
  168. Message = Encoding.ASCII.GetString( bMessage );
  169. Console.ForegroundColor = ConsoleColor.Cyan;
  170. Console.Write( "Recieved: \t" );
  171. Console.ForegroundColor = ConsoleColor.White;
  172. Console.WriteLine( Message );
  173.  
  174. byte[] NewMes = Encoding.ASCII.GetBytes( Client.Name + ": " + Message );
  175. foreach( Client c in Clients )
  176. c.Stream.Write( NewMes, 0, NewMes.Length );
  177. }
  178. catch
  179. {
  180. Console.WriteLine( "Lost connection with " + Client.Name );
  181. break;
  182. }
  183. }
  184.  
  185. ClientStream.Dispose();
  186. ClientStream.Close();
  187. Clients.Remove( Client );
  188. Connected--;
  189. }
  190.  
  191. public class Client
  192. {
  193. public NetworkStream Stream;
  194. public int ID;
  195. public string Name;
  196. public Client( string name, int id, NetworkStream stream )
  197. {
  198. Name = name;
  199. ID = id;
  200. Stream = stream;
  201. }
  202. }
  203. }
  204. }


Client chat form
CSHARP Code
  1. using System;
  2. using System.Text;
  3. using System.Windows.Forms;
  4. using System.Net.Sockets;
  5.  
  6. namespace Client
  7. {
  8. public partial class ChatForm : Form
  9. {
  10. NetworkStream Stream;
  11. public ChatForm( NetworkStream Stream )
  12. {
  13. InitializeComponent();
  14. this.Stream = Stream;
  15.  
  16. new System.Threading.Thread( () =>
  17. {
  18. byte[] buffer;
  19. int Recieved;
  20. while( true )
  21. {
  22. try
  23. {
  24. buffer = new byte[1024];
  25. Recieved = this.Stream.Read( buffer, 0, buffer.Length );
  26. Array.Resize( ref buffer, Recieved );
  27.  
  28. Invoke( ( MethodInvoker ) delegate
  29. {
  30. MessageBox.Text += Encoding.ASCII.GetString( buffer ) + "\r\n";
  31. } );
  32. }
  33. catch( Exception e )
  34. {
  35. System.Windows.Forms.MessageBox.Show( "Disconnected! \r\n" + e.Message );
  36. Environment.Exit( 0 );
  37. }
  38. }
  39. } ).Start();
  40. }
  41.  
  42. private void button1_Click( object sender, EventArgs e )
  43. {
  44. byte[] buffer = Encoding.ASCII.GetBytes( TextBox.Text );
  45. this.Stream.Write( buffer, 0, buffer.Length );
  46. this.Stream.Flush();
  47. TextBox.Text = "";
  48. }
  49.  
  50. private void TextBox_KeyPress( object sender, KeyPressEventArgs e )
  51. {
  52. if( e.KeyChar == ( char )Keys.Enter )
  53. button1_Click( new object(), new EventArgs() );
  54. }
  55. }
  56. }


Client login form
CSHARP Code
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.Net;
  6. using System.Net.Sockets;
  7.  
  8. namespace Client
  9. {
  10. public partial class LoginForm : Form
  11. {
  12. public LoginForm()
  13. {
  14. InitializeComponent();
  15. }
  16.  
  17. private void button1_Click( object sender, EventArgs e )
  18. {
  19. try
  20. {
  21. TcpClient Client = new TcpClient();
  22. IPEndPoint IP = new IPEndPoint(
  23. IPAddress.Parse( IPBox.Text ),
  24. Convert.ToInt32( PortBox.Text )
  25. );
  26.  
  27. if( !Login( NameBox.Text, PwBox.Text ) )
  28. {
  29. MessageBox.Show( "Invalid password or username!\r\n" +
  30. "Are you sure this account exists?" );
  31. return;
  32. }
  33.  
  34. Client.Connect( IP );
  35. NetworkStream stream = Client.GetStream();
  36. byte[] buffer = Encoding.ASCII.GetBytes( "#info " + GetRealName( NameBox.Text ) );
  37. stream.Write( buffer, 0, buffer.Length );
  38. stream.Flush();
  39. ChatForm Chat = new ChatForm( stream );
  40. Chat.Show();
  41. this.Hide();
  42. }
  43. catch( Exception ex )
  44. {
  45. MessageBox.Show( ex.ToString() );
  46. }
  47. }
  48.  
  49. string GetRealName( string name )
  50. {
  51. WebClient wb = new WebClient();
  52. string source = wb.DownloadString( "http://www.itsmods.com/forum/User-" + name + ".html" );
  53. int title = source.IndexOf( "<title>" );
  54. wb.Dispose();
  55. return source.Substring( title + 30, name.Length ).Trim();
  56. }
  57.  
  58. private bool Login( string User, string Password )
  59. {
  60. System.Collections.Specialized.NameValueCollection Data
  61. = new System.Collections.Specialized.NameValueCollection();
  62. Data.Add( "username", User );
  63. Data.Add( "password", Password );
  64. Data.Add( "submit", "Login" );
  65. Data.Add( "action", "do_login" );
  66.  
  67. WebClient wb = new WebClient();
  68. byte[] bytes = wb.UploadValues( "http://itsmods.com/forum/member.php", "POST", Data );
  69.  
  70. if( System.Text.Encoding.ASCII.GetString( bytes ).Contains( "successfully" ) )
  71. return true;
  72.  
  73. return false;
  74. }
  75. }
  76. }


Full source code:

.rar   BasicServer.rar (Size: 84.75 KB / Downloads: 213)


Please give some advice in case you know a better/faster way of doing this Smile

pic:
[Image: mzembi45dN.png]

edit: yes I know the maximum amount of clients is bullshit and doesn't do anything but I got bored so I didn't finish that Big Grin
(08-10-2011, 12:58)Pozzuh Wrote:
Se7en Wrote:Stealed, from cod4 mod ...
look who's talking

[Release] Old School Mod v2.2
[Release] Scroll menu

Reply

#2
looks very cool
C++/Obj-Cdeveloper. Neko engine wip
Steam: Click
Reply

#3
Good job @ieagle
[Image: lQDUjba.jpg]
Reply

#4
Nice one.

[Image: r212360a129ce9b84444093b6cd2699013a1fbn155.png]
Reply

#5
(02-08-2012, 16:34)G-Man Wrote: Nice one.


This is not for actual use (unless you feel like using this instead of skype/msn/irc etc.). I just wanted to learn how to use simple network code.
(08-10-2011, 12:58)Pozzuh Wrote:
Se7en Wrote:Stealed, from cod4 mod ...
look who's talking

[Release] Old School Mod v2.2
[Release] Scroll menu

Reply

#6
(02-08-2012, 16:57)iAegle Wrote:
(02-08-2012, 16:34)G-Man Wrote: Nice one.


This is not for actual use (unless you feel like using this instead of skype/msn/irc etc.). I just wanted to learn how to use simple network code.

I said that "nice one" as i know that your work is much harder and idk if i can do same)) the thing you made is also a chat but it has another working system (much better than just web-chat) me just Dumb Bitch
[Image: r212360a129ce9b84444093b6cd2699013a1fbn155.png]
Reply

#7
thanks for your work
Reply

#8
I set to multiple start up projects give error 404
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Release] Windows 8.1 Fix for MW3 Server Addon master131 16 18,189 09-29-2014, 23:08
Last Post: SuperNovaAO
Brick [Release] MW3 Server Administration Addon iRoNinja 5 9,011 11-10-2013, 15:46
Last Post: Casper
Exclamation Help cmdlist, dvarlist server crash Nerus 17 11,912 11-09-2013, 23:54
Last Post: Nerus
  Our Level Fastfile is Different from the Server. CheeseToast 6 11,322 11-03-2013, 17:52
Last Post: CheeseToast
  Dedicated Server External (public) IP Nerus 3 5,901 11-02-2013, 14:16
Last Post: Casper
  MW3 Server Version superg1973 7 12,746 10-28-2013, 01:15
Last Post: kotyra972
  Help how to turn off map in dedicated server pero123 8 7,132 10-15-2013, 19:00
Last Post: Nekochan
  Issue with server addon and NAT dimitrifrom31 3 5,082 10-08-2013, 18:11
Last Post: iRoNinja
  GETTING SERVER ONLINE raym 6 5,713 09-28-2013, 22:42
Last Post: Nekochan
  advanced Server Config Poorya56 9 7,018 09-11-2013, 03:45
Last Post: trasto

Forum Jump:


Users browsing this thread:
3 Guest(s)

Forum Powered By MyBB, Theme by © 2002-2024 Melroy van den Berg.