Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8854103
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T13:48:33+00:00 2026-06-14T13:48:33+00:00

i have a bare bones chat client in console. Here’s the code For server

  • 0

i have a bare bones chat client in console. Here’s the code

For server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace chat_server
{
 class Program
{
    static TcpListener server = new TcpListener(IPAddress.Any, 9999);

    static void input(object obs)
    {
        StreamWriter writer = obs as StreamWriter;
        string op = "nothing";
        while (!op.Equals("exit"))
        {
            Console.ResetColor();
            Console.WriteLine("This is the " + Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Enter your text(type exit to quit)");
            op = Console.ReadLine();
            writer.WriteLine(op);
            writer.Flush();
        }
    }

    static void output(Object obs)
    {
        StreamReader reader = obs as StreamReader;
        Console.ForegroundColor = ConsoleColor.Green;
        while (true)
        {
            Console.WriteLine(reader.ReadLine());
        }
    }

    static void monitor()
    {
        while (true)
        {
            TcpClient cls = server.AcceptTcpClient();
            Thread th = new Thread(new ParameterizedThreadStart(mul_stream));
            th.Start(cls);
        }
    }

    static void mul_stream(Object ob)
    {
        TcpClient client = ob as TcpClient;
        Stream streams = client.GetStream();
        StreamReader reads = new StreamReader(streams);
        StreamWriter writs = new StreamWriter(streams);

        new Thread(new ParameterizedThreadStart(output)).Start(reads);
        input(writs);
    }

    static void Main(string[] args)
    {

        server.Start();
        monitor();
        server.Stop();
        Console.ReadKey();
    }
 }
}

and here’s the client code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace chat_client
{
 class Program
 {
    static StreamReader reader;
    static StreamWriter writer;
    static Thread input_thread;

    static void input()
    {
        string op = "nothing";
        while (!op.Equals("exit"))
        {
            Console.ResetColor();
            Console.WriteLine("Enter your text(type exit to quit)");
            op = Console.ReadLine();
            writer.WriteLine(op);
            writer.Flush();
        }
    }

    static void output()
    {
        Console.ForegroundColor = ConsoleColor.Blue;
        while (true)
        {
            Console.WriteLine(reader.ReadLine());
        }
    }


    static void Main(string[] args)
    {
        Console.WriteLine("Enter the ip address");
        string ip = Console.ReadLine();
        TcpClient client = new TcpClient(ip,9999);

        NetworkStream stream = client.GetStream();
        reader = new StreamReader(stream);
        writer = new StreamWriter(stream);

        input_thread = new Thread(input);
        input_thread.Start();

        /*
        writer.Write("Hello world");
        writer.Flush();
        Console.WriteLine("Message Sent");*/
        output();
        client.Close();
        Console.ReadKey();
    }
 }
}

Now the thing is that i am having some issues converting this code to GUI. For instance the input function in the server which delivers the message through a specific stream to a client should be somewhat equivalent to SEND button in GUI.

However each thread creates its own stream and i don’t think that creating seprate event handlers on different threads would be a good idea.

In short i need some advice on where to start with this project.

Thank you.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T13:48:34+00:00Added an answer on June 14, 2026 at 1:48 pm

    Networking is hard. Your current approach, which is just reading everything and treating everything as complete messages, is fragile. It works during debugging but will fail during production since TCP is stream based.

    Instead, you could use an existing framework to abstract away the networking layer. As it happens, I’ve made a framework which is open source (LGPL).

    In this case we’ll just want to be able to chat. So I added a chat message definition like this:

    public class ChatMessage
    {
        public DateTime CreatedAt { get; set; }
        public string UserName { get; set; }
        public string Message { get; set; }
    }
    

    That message is put in a shared assembly (used both by the client and the server).

    The server itself is defined like this:

    public class ChatServer : IServiceFactory
    {
        private readonly List<ClientChatConnection> _connectedClients = new List<ClientChatConnection>();
        private readonly MessagingServer _server;
    
    
        public ChatServer()
        {
            var messageFactory = new BasicMessageFactory();
            var configuration = new MessagingServerConfiguration(messageFactory);
            _server = new MessagingServer(this, configuration);
        }
    
        public IServerService CreateClient(EndPoint remoteEndPoint)
        {
            var client = new ClientChatConnection(this);
            client.Disconnected += OnClientDisconnect;
    
            lock (_connectedClients)
                _connectedClients.Add(client);
    
            return client;
        }
    
        private void OnClientDisconnect(object sender, EventArgs e)
        {
            var me = (ClientChatConnection) sender;
            me.Disconnected -= OnClientDisconnect;
            lock (_connectedClients)
                _connectedClients.Remove(me);
        }
    
        public void SendToAllButMe(ClientChatConnection me, ChatMessage message)
        {
            lock (_connectedClients)
            {
                foreach (var client in _connectedClients)
                {
                    if (client == me)
                        continue;
    
                    client.Send(message);
                }
            }
        }
    
        public void SendToAll(ChatMessage message)
        {
            lock (_connectedClients)
            {
                foreach (var client in _connectedClients)
                {
                    client.Send(message);
                }
            }
        }
    
        public void Start()
        {
            _server.Start(new IPEndPoint(IPAddress.Any, 7652));
        }
    }
    

    See? No networking code anywhere.

    The client is event easier:

    static class Program
    {
        private static MainForm _mainForm;
        private static MessagingClient _client;
    
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
    
            ConfigureChat();
            _mainForm = new MainForm();
            Application.Run(_mainForm);
        }
    
        private static void ConfigureChat()
        {
            _client = new MessagingClient(new BasicMessageFactory());
            _client.Connect(new IPEndPoint(IPAddress.Loopback, 7652));
            _client.Received += OnChatMessage;
        }
    
        private static void OnChatMessage(object sender, ReceivedMessageEventArgs e)
        {
            _mainForm.InvokeIfRequired(() => _mainForm.AddChatMessage((ChatMessage)e.Message));
        }
    
        public static void SendChatMessage(ChatMessage msg)
        {
            if (msg == null) throw new ArgumentNullException("msg");
            _client.Send(msg);
        }
    }
    

    enter image description here

    The full example is available here: https://github.com/jgauffin/Samples/tree/master/Griffin.Networking/ChatServerClient

    Update:

    Since it’s a school project and you can’t use anything other than .NET I would probably use the easiest possible approach. And that’s to use new line ("\r\n") as delimiter.

    so in each side you just used var chatMessage = streamReader.ReadLine() and streamWriter.WriteLine("Chat message");

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a bare-bones install of jenkins on my Ubuntu server that I installed
I have a bare-bones sample project here: http://dl.dropbox.com/u/7834263/ExpandingCells.zip In this project, a UITableView has
I have been trying to write a bare-bones ping scanner using Perl for internal
I have the code below (a bare-bones version of Nehe tutorial 1 ported to
See code below. I've tried to strip it to its bare bones. I have
I'm using PHP's built in IMAP functions to build a bare-bones webmail client (will
I have a bare repository initialize on my webserver. I code on my workstation
I have stripped the following back to the bare bones, I am passing more
Suppose I have a garden-variety closure like this bare-bones sample: (let ((alpha 0) #|
I have some code that is crashing in a large system. However, the code

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.