Duskk
Duskk

Reputation: 1

C# How do I send data to all clients connected to my server?

So I'm trying to create a chat application but I'm new to sockets. I have followed a tutorial to create a server and client, however, the server does not broadcast the data sent from one client to every client connected to it. Instead, it only broadcasts it to the client that sent the data.

I have tried to add every client who joins the server to a list and then use a foreach loop to send the data received from one client to every client in the list. This, however, has not worked. I suspect that the error is in the foreach loop but I am not completely certain.

Here is my code for the server:

class Program
{
    public static List<Socket> connectedClient = new List<Socket>();
    public static Socket clientSocket = default(Socket);

    static void Main(string[] args)
    {

        int port = 13000;
        string IpAddress = "127.0.0.1";

        Socket serverListener = new Socket(AddressFamily.InterNetwork, 
        SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpAddress), port);
        serverListener.Bind(ep);
        serverListener.Listen(0);
        Console.WriteLine("Server running");

        Program p = new Program();

        int counter = 0;
        while (true)
        {
            counter++;
            clientSocket = serverListener.Accept();
            connectedClient.Add(clientSocket);
            Console.WriteLine(counter + " Client joined");

            Thread clientThread = new Thread(new ThreadStart(() => 
            p.User(clientSocket)));
            clientThread.Start();
        }
    }

    public void User(Socket client)
    {
        while (true)
        {
            byte[] msg = new byte[1024];
            int size = client.Receive(msg);
            Console.WriteLine("Client>> " + 
            System.Text.Encoding.ASCII.GetString(msg, 0, size));

            //the loop that i tried to implement
            foreach(Socket clientSocket in connectedClient)
            {
                client.Send(msg, 0, size, SocketFlags.None);
            }
        }
    }
}

Instead of the message being broadcasted once to all clients, the server sends the message back to the client who sent it but times how many clients there are.

For example: If there are 4 clients connected to the server and one client sends a message "Hello" the server will send back "HelloHelloHelloHello" but only to the client who sent the "Hello".

Upvotes: 0

Views: 1920

Answers (1)

N.D.C.
N.D.C.

Reputation: 1601

In

foreach(Socket clientSocket in connectedClient)
    {
        client.Send(msg, 0, size, SocketFlags.None);
    }

You are looping over the clientSockets, but you are Sending on the client, not the clientSocket. If you do clientSocket.Send instead, you should get the expected behavior (e.g. send to each client instead of to one client 4 times).

Upvotes: 2

Related Questions