multithreading - c# TCP Server Client Threading Issies -
here problem, have below scenario coded.
- a tcp listener running in thread connecting client 1
- a second tcp listener running in thread b connecting multiple clients each in different thread. mean client accepted in thread b, different thread created further processing of client waits data "tcp listener b" in while loop
what want , i'm facing problem is,
i want pass data recieved thread 1 client 1 clients in thread 2.
what believe happening,
since i'm in thread 1 when data client 1 in thread 1, when try sending data clients in thread 2, connection false.
is threading issue?
how can overcome issue?
edit
it's windows form application
both tcp listener run in same application.
i'm maintaining list of tcpclients connect tcp listener b , when data thread a, tcp client list maintain , try send data, cannot connection state becomes false.
i've had same problem, used backgroundworker instead of thread handle clients. here extracted code project:
private static void bw_dowork(object sender, doworkeventargs e) { listener.start(); while (!bw.cancellationpending) { tcpclient client = listener.accepttcpclient(); threadpool.queueuserworkitem(threadproc, client); } listener.stop(); }
and in threadproc handling every client
private static void threadproc(object state) { var client = (tcpclient)state; clientslist.add(client); handleclient hclient = new handleclient(); hclient.startclient(client); //do whatever client here }
and broadcast information did
public static void broadcast(byte[] msg, string uname) { foreach (tcpclient item in clientslist) { if (item != null) { try { tcpclient broadcastsocket; broadcastsocket = item; networkstream broadcaststream = broadcastsocket.getstream(); byte[] broadcastbytes = null; broadcastbytes = msg; debug.writeline("send data " + uname); broadcaststream.write(broadcastbytes, 0, broadcastbytes.length); broadcaststream.flush(); } catch (exception) { //handle exceptions .... } } } }
i hope helps. can @ finished project @ https://github.com/hrkrx/montagsmalervs examples hostcontroller.cs
Comments
Post a Comment