How to pass messages between multiple threads?

A

Adam

My telnet server app. creates a new thread for each incoming Tcp client as
shown in the code below. How can the client threads send text messages back
and forth to each other? I don't understand how separate threads can
communicate directly. Any techniques I can use?
Thanks!

//LISTENER THREAD
class Server
{
static void Main(string[] args)
{
Socketserver server=new Socketserver();
}

class Socketserver
{
int port=8000;
private TcpListener client;
public Socketserver()
{
client = new TcpListener(IPAddress.Any,port);
client.Start();
while(true)
{
while (!client.Pending())
{Thread.Sleep(1000);}
Newclientthread newconnection=new Newclientthread();
newconnection.threadListener=this.client;
//Create the client thread here for as many connections that
come in.
Thread newthread = new Thread(new
ThreadStart(newconnection.Sendreceiveloop));
newthread.Start();
}
}
}

//CLIENT THREAD SPAWNED BY THE LISTENER:
class Newclientthread
{
public TcpListener threadListener;
public static int connections=0;
public void Sendreceiveloop()
{
Socket ns=threadListener.AcceptSocket();
connections++;
try
{
Sendtext(ns,clientep,"Welcome to chat!!!!");
}
catch (Exception ex)
{
Disconnectclient(ns);
}
}
 
S

Sherif ElMetainy

Hello

You can use events as a method for thread communications.
See System.Threading.ManualResetEvent and System.Threading.AutoResetEvent
classes in .NET Framework documentation. You can have an arraylist to store
messages, a thread that waits for an event. When a thread wants to send a
message it puts the message in the arraylist, then sets the event, The
waiting thread can wakeup process all the messages in the list, reset the
event and wait again.

For performance consider using System.Threading.ThreadPool instead of
spawning a new thread for every connected client. Also use
System.Threading.Interlocked.Inecrement instead of connections++

Best Regards
Sherif
 
G

Greg Ewing [MVP]

Adam, one way to do this communication would be with events. You could
create your own event with your own EventArgs. When you create each thread
make it listen for your event. When you want one thread to say something to
another thread just throw your event with the approriate EventArgs. Hope
that helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top