I'm facing a weird trouble with sockets and threads. It's a simple multithread server-clients, a just wan't to send and receive messages.
Here's the server code:
public class Server
{
Thread t;
Thread listen;
byte[] data1;
byte[] data2;
NetworkStream ns;
TcpClient client;
TcpListener newsock;
public bool Running;
List<ClStr> ListOfStreams = new List<ClStr>();
List<ClientList> ListOfClients = new List<ClientList>();
public Server()
{
Listen = new Thread(new ThreadStart(ExecuteThread));
Listen.Start();
}
private void ExecuteThread()
{
newsock = new TcpListener(Globals.ServerPort);
newsock.Start();
Running = true;
LoopClients();
}
public void LoopClients()
{
try
{
while (Running)
{
client = newsock.AcceptTcpClient();
t = new Thread(new ParameterizedThreadStart(NewClient));
t.Start(client);
ClientList LCli = new ClientList(client);
ListOfClientes.Add(LCli);
}
}
catch (SocketException e)
{
MessageBox.Show(e.ToString());
}
finally
{
newsock.Stop();
}
}
private void NewClient(object obj)
{
TcpClient client = (TcpClient)obj;
ns = client.GetStream();
ClStr Cli = new ClStr(ns);
ListOfStreams.Add(Cli);
string TicketDelivery = "TKT:" + Cli.Ticket.ToString();
byte[] TKTbuffer = Encoding.ASCII.GetBytes(TicketDelivery);
ns.Write(TKTbuffer, 0, TKTbuffer.Length);
while (true)
{
int recv;
data2 = new byte[200 * 1024];
recv = ns.Read(data2, 0, data2.Length);
if (recv == 0)
break;
MessageBox.Show(Encoding.ASCII.GetString(data2, 0, recv));
}
}
Note that every new client is a new thread. No problem until here.
See the client code.
public class Client
{
Thread Starter;
Socket server;
byte[] data;
string stringData;
int recv;
public int Ticket;
public void Connect()
{
data = new byte[200 * 1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), Port);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
server.Connect(ipep);
Starter = new Thread(new ThreadStart(execute));
Starter.Start();
}
catch (SocketException e)
{
MessageBox.Show("Unable to connect to server.");
Starter.Abort();
return;
}
}
public void SendMessageToServer(string msg)
{
server.Send(Encoding.ASCII.GetBytes(msg));
}
private void execute()
{
while (true)
{
data = new byte[200 * 1024];
recv = server.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
byte[] byteData = data;
MessageBox.Show(stringData);
}
}
Now here's the problem:
I can only send an message to server (using the method SendMessageToServer) from the last client connected to server. If I add 3 clients, and try to send an message with first added, nothing happens! It seems that the client is not connected to the socket, but is not true, because I can send messages from the server with no problem.
So, considering that the server creates one thread per client, how can I send messages to server from any connected client?