Christian Wiles

Christian Wiles

  • NA
  • 2
  • 2.4k

Help needed with my Chat Server and Client

May 23 2014 9:37 PM
I have wrote a console chat server, using NetworkStream, TcpListener, and ClientStreams. The server lets you choose amount of people to allow to connect to it and the port it will broadcast on. I am now stumped and have been for the past couple of months, I don't know where to begin on writing the client, I want the client to be in console, allow you to choose the ip and port to connect to and a nickname for yourself, I have no idea how to do this so, I ask, please make me some basic code to connect to the server and send a message, I should be able to take it from there. Below I will post the code for the server. Thanks Guys :)

<!--START CODE-->
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;


namespace BasicServer
{
    class Program
    {
        static PerformanceCounter cpuUsage;
        static TcpListener Listener;
        static List<Client> Clients = new List<Client>();
        static int Port = -1, MaxClients = -1, Connected = 0;
        static void Main(string[] args)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            string webData = wc.DownloadString("http://echoip.net");
            DateTime datetime = DateTime.Now;
            Console.Title = "xy3lay(SERVER)";
            Console.ForegroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.DarkBlue;
            Console.WriteLine("@                                xy3lay(SERVER)                                @");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.WriteLine("Opened: " + datetime + " * " + "IPv4: " + webData + " * " + "Working Set: " + Environment.WorkingSet);
            Console.WriteLine("!------------------------------------------------------------------------------!");
            Console.ForegroundColor = ConsoleColor.Gray;
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].ToLower() == "+port")
                {
                    Port = Convert.ToInt32(args[i + 1]);
                    i++;
                    continue;
                }


                if (args[i].ToLower() == "+maxclients")
                {
                    MaxClients = Convert.ToInt32(args[i + 1]);
                    i++;
                    continue;
                }
            }
            Console.Write("Configure: ");
            while (MaxClients < 1)
            {
                Console.Write("Enter the maximum amount of clients(1 or more): ");
                MaxClients = Convert.ToInt32(Console.ReadLine());
            }


            if (Port == -1)
            {
                Console.Write("Please enter the port that you want to use: ");
                Port = Convert.ToInt32(Console.ReadLine());
            }


            Console.Write("Trying to start the server at port " + Port + ": ");


            try
            {
                Listener = new TcpListener(System.Net.IPAddress.Any, Port);
                Listener.Start();


                new Thread(() =>
                {
                    while (true)
                    {
                        TcpClient Client = Listener.AcceptTcpClient();
                        Thread ClientThread = new Thread(new ParameterizedThreadStart(ClientMain));
                        ClientThread.Start(Client);
                        Connected++;
                    }
                }).Start();
                System.Net.WebClient wc2 = new System.Net.WebClient();
                string webData2 = wc2.DownloadString("http://echoip.net");
                new Thread(new ThreadStart(ReadConsole)).Start();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Success!");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write("IPv4 Broadcast Address: ");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write(webData2 + ":" + Port);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Failed!");
                Console.WriteLine("Error: " + e.Message);
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(0);
            }


            System.Diagnostics.Process.GetCurrentProcess().WaitForExit();
        }
       
        public static IPAddress GetIPAddress(string hostName)
        {
            Ping ping = new Ping();
            var replay = ping.Send(hostName);


            if (replay.Status == IPStatus.Success)
            {
                return replay.Address;
            }
            return null;
        }
        static void SendToClient(NetworkStream Client, string Text)
        {
            byte[] buffer = Encoding.ASCII.GetBytes(Text);
            Client.Write(buffer, 0, buffer.Length);
            Client.Flush();
        }


        static void ReadConsole()
        {
            string Text;
            while (true)
            {
                Text = Console.ReadLine();


                if (Text == "quit")
                {
                    foreach (Client c in Clients)
                    {
                        c.Stream.Dispose();
                        c.Stream.Close();
                    }
                    Environment.Exit(0);
                }


                if (Text.Split(' ')[0].ToLower() == "say")
                {
                    if (Connected <= 0)
                    {
                        Console.WriteLine("No clients connected ... ");
                        continue;
                    }


                    try
                    {
                        foreach (Client c in Clients)
                            SendToClient(
                                c.Stream,
                                "Server: " + Text.Substring(4)
                            );


                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write("Send: \t\t");
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine(Text.Substring(4));
                    }
                    catch (Exception e) { Console.WriteLine(e.Message); }
                }
            }
        }
        static void ClientMain(object obj)
        {
            TcpClient NewClient = (TcpClient)obj;
            NetworkStream ClientStream = NewClient.GetStream();


            int ID = Connected;
            byte[] bMessage = new byte[1024];
            string Message;
            int Recieved = ClientStream.Read(bMessage, 0, bMessage.Length);
            Array.Resize(ref bMessage, Recieved);


            if (!Encoding.ASCII.GetString(bMessage).StartsWith("#info"))
            {
                Console.WriteLine("Someone tried to connect but it failed!");
                ClientStream.Dispose();
                ClientStream.Close();
                return;
            }


            string Name = Encoding.ASCII.GetString(bMessage);
            Client Client = new Client(Name.Substring(6), ID, ClientStream);
            Clients.Add(Client);
            Console.WriteLine("New connection: " + Client.Name);


            while (true)
            {
                Recieved = 0;
                bMessage = new byte[1024];
                try
                {
                    Recieved = ClientStream.Read(bMessage, 0, bMessage.Length);
                    Array.Resize(ref bMessage, Recieved);
                    Message = Encoding.ASCII.GetString(bMessage);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("Recieved: \t");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine(Message);


                    byte[] NewMes = Encoding.ASCII.GetBytes(Client.Name + ": " + Message);
                    foreach (Client c in Clients)
                        c.Stream.Write(NewMes, 0, NewMes.Length);
                }
                catch
                {
                    Console.WriteLine("Lost connection with " + Client.Name);
                    break;
                }
            }


            ClientStream.Dispose();
            ClientStream.Close();
            Clients.Remove(Client);
            Connected--;
        }


        public class Client
        {
            public NetworkStream Stream;
            public int ID;
            public string Name;
            public Client(string name, int id, NetworkStream stream)
            {
                Name = name;
                ID = id;
                Stream = stream;
            }
        }
    }
}
<!--END CODE-->