Hello I am new to threads and I don't have too much idea. So as to
learn I was thinking to create a simple multithreaded server. There
are several clients that send data to the server as a kind of chat
and in the server must be printed all the messages sent by different
clients.
If I run only one client it works fine. In case I run several it only
works well when I am writing in the last client open. If i try to go
back and write in one that was opened before I only can get one line
printed and then it gets blocked. It's quite obvious that it's a
thread problem because it's just paying attention to the last one
opened and not the rest.
Here is the code for the server, cos clients just only use a simple
thread and it seems it works fine.
#include "server.h"
Server::Server()
{
readThread=new Thread(new ThreadStart(this,RunServer));
readThread->Start();
}
void Server::RunServer()
{
TcpListener *listener;
try{
listener=new TcpListener(4500);
listener->Start();
Console::WriteLine(S"Waiting for connection\r\n");
while(true){
connection=listener->AcceptSocket();
if (connection->Connected){
mythread=new Thread(new ThreadStart(this,engine));
mythread->Start();
counter++;
}
}
connection->Close();
}
catch(Exception *error){
MessageBox::Show(error->ToString());
}
}
void Server::engine(){
socketStream=new NetworkStream(connection);
writing=new BinaryWriter(socketStream);
reading=new BinaryReader(socketStream);
Console::WriteLine(S"\r\nConnection {0}
received",counter.ToString());
writing->Write(S"SERVER>>> Connection succesfull");
String *theReply=S"";
do{
try{
theReply=reading->ReadString();
Console::WriteLine(S"\r\n {0}",theReply);
}
catch (Exception *){
break;
}
}while(!theReply->Equals(S"CLIENT>>>
TERMINATE")&&connection->Connected);
socketStream->Close();
writing->Close();
reading->Close();
Console::WriteLine(S"\r\nUser terminated connection");
}
Sorry for my ingnorance about threads. I hope someone helps me. Also I
haven't found any website that explains well threads.