I try to create a server program in console with C#. I use ThreadPool to create separate socket for each clients. Then, I create a static List<TcpClient> clients = new List<TcpClient>();
to contains all clients connected to.
Then, what I want is, when 1 client send to server a message, server will receive and send it out to all client connected. So, I wrote:
foreach (var item in clients)
{
ns.Write(data, 0, recv);
//send message to all client
}
But, only client just sent the message can receive it back, another clients was receive nothing!
**** Server side:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class ThreadedTcpSrvr
{
private TcpListener client;
//private
public ThreadedTcpSrvr()
{
client = new TcpListener(IPAddress.Parse("127.0.0.1"), 9050);
client.Start();
Console.WriteLine("Waiting for clients...");
while (true)
{
while (!client.Pending())
{
Thread.Sleep(1000);
}
ConnectionThread newconnection = new ConnectionThread();
newconnection.threadListener = this.client;
Thread newthread = new Thread(new
ThreadStart(newconnection.HandleConnection));
newthread.Start();
}
}
public static void Main()
{
ThreadedTcpSrvr server = new ThreadedTcpSrvr();
}
}
class ConnectionThread
{
static List<TcpClient> clients = new List<TcpClient>();
public TcpListener threadListener;
private static int connections = 0;
public void HandleConnection()
{
int recv;
byte[] data = new byte[1024];
TcpClient client = threadListener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
//TcpClient clientSocket = client.AccepTcpClient();
clients.Add(client);
connections++;
Console.WriteLine("New client accepted: {0} active connections",
connections);
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
while (true)
{
data = new byte[1024];
recv = ns.Read(data, 0, data.Length);
if (recv == 0)
break;
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
//ns.Write(data, 0, recv);
foreach (var item in clients)
{
ns.Write(data, 0, recv);
//send message to client
}
}
ns.Close();
client.Close();
connections--;
Console.WriteLine("Client disconnected: {0} active connections",connections);
}
}
**** Client side:
void ReceiveData(IAsyncResult iar)
{
try
{
while(true)
{
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceive(iar);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
ListAddItem(stringData);
}
}
catch
{
}
}