multithreading - How to spread tcplistener incoming connections over threads in .NET? -
when using net.sockets.tcplistener, best way handle incoming connections (.acceptsocket) in seperate threads?
the idea start new thread when new incoming connection accepted, while tcplistener stays available further incoming connections (and every new incoming connection new thread created). communication , termination client originated connection handled in thread.
example c# of vb.net code appreciated.
the code i've been using looks this:
class server { private autoresetevent connectionwaithandle = new autoresetevent(false); public void start() { tcplistener listener = new tcplistener(ipaddress.any, 5555); listener.start(); while(true) { iasyncresult result = listener.beginaccepttcpclient(handleasyncconnection, listener); connectionwaithandle.waitone(); // wait until client has begun handling event connectionwaithandle.reset(); // reset wait handle or loop goes fast can (after first request) } } private void handleasyncconnection(iasyncresult result) { tcplistener listener = (tcplistener)result.asyncstate; tcpclient client = listener.endaccepttcpclient(result); connectionwaithandle.set(); //inform main thread connection handled //... use tcpclient here client.close(); } }
Comments
Post a Comment