GytisK
GytisK

Reputation: 169

C# Chat clients with multiple threads (read+write at the same time)

How do I make the client read from the stream (for messages of other clients sent to the stream) at the same time as being able to write to them?

I tried creating different threads on the client side (did I even do it right?), however I can still only write to the server, without any response. This is what I'm getting right now:

(Server-Client-Client)

Client:

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


namespace Klientas
{
    class Klientas
    {
        public static void Write()
        {
            while (true)
            {
                TcpClient clientSocket = new TcpClient("localhost", 1000);
                string str = Console.ReadLine();
                BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
                writer.Write(str);
            }
        }
        public static void Read()
        {
            while (true)
            {
                TcpClient clientSocket = new TcpClient("localhost", 1000);
                BinaryReader reader = new BinaryReader(clientSocket.GetStream());
                Console.WriteLine(reader.ReadString());
            }
        }

        static void Main(string[] args){
            Thread ctThread = new Thread(Write);
            Thread ctThread2 = new Thread(Read);
            ctThread2.Start();
            ctThread.Start();

           }
    }    
}

Server:

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

namespace MultiServeris
{
    class Multiserveris
    {
        static void Main(string[] args)
        {
            TcpListener ServerSocket = new TcpListener(1000);          
            ServerSocket.Start();                                    

            Console.WriteLine("Server started.");
            while (true)
            {
                TcpClient clientSocket = ServerSocket.AcceptTcpClient();       
                handleClient client = new handleClient();                      
                client.startClient(clientSocket);
            }


        }
    }

    public class handleClient
    {
        TcpClient clientSocket;                                   
        public void startClient(TcpClient inClientSocket)
        {
            this.clientSocket = inClientSocket;
            Thread ctThread = new Thread(Chat);                   
            ctThread.Start();
        }



        private void Chat()
        {                  
            while (true)
            {
                BinaryReader reader = new BinaryReader(clientSocket.GetStream());
                Console.WriteLine(reader.ReadString());
            }
        }



    }

}

Upvotes: 0

Views: 4373

Answers (2)

Stilgar
Stilgar

Reputation: 23551

It seems like you do not have any code on the server to send messages to the client. You need to maintain a list of connected clients and make the server send a message to the eligible clients when it receives a message. Also do not make the client a console app. Unlike most projects for a chat client it is actually harder to do it as a console app.

To keep a list of clients you declare a list of TCP Clients like this

static List<TcpClient> clients = new List<TcpClient>();

Then when a client connects you add it to the list

TcpClient clientSocket = ServerSocket.AcceptTcpClient();  
clients.Add(clientSocket);

Then when you receive a message you send it to all clients

BinaryReader reader = new BinaryReader(clientSocket.GetStream());
while(true)
{
    string message = reader.ReadString();
    foreach(var client in clients)
    {
        //send message to client
    }
}

Now remember that in practice you should handle things like disconnects and adding and removing clients from the list should be thread safe (locks and all).

Upvotes: 2

Tomasito
Tomasito

Reputation: 1883

Good starting point for socket client-server communication: demo application and library. Support for reconnecting, sudden client disconnect catch, message broadcasting and many more.

Upvotes: 0

Related Questions