c# - TCP server with multiple Clients -
i working on tcp server/client application.
my question is:
my server application starts new thread , blocks until connection accepted listenforclient method
but how can manage connections when multiple clients connected server , request different things @ same time how can manage client 1 gets info need , same client 2.
it's multithreaded, multiple clients can connect how can process request. don't want put in 1 method would.
thanks in advance
private void serverstart() { this.tcplistener = new tcplistener(ipaddress.any, 49151); this.listenthread = new thread(new threadstart(listenforclients)); this.listenthread.start(); } private void listenforclients() { this.tcplistener.start(); while (true) { //blocks until client has connected server tcpclient client = this.tcplistener.accepttcpclient(); // here first message send hello client // /////////////////////////////////////////////////// //create thread handle communication //with connected client thread clientthread = new thread(new parameterizedthreadstart(handleclientcomm)); clientthread.start(client); } } private void handleclientcomm(object client) { tcpclient tcpclient = (tcpclient)client; networkstream clientstream = tcpclient.getstream(); byte[] message = new byte[4096]; int bytesread; while (true) { bytesread = 0; try { //blocks until client sends message bytesread = clientstream.read(message, 0, 4096); } catch { //a socket error has occured break; } if (bytesread == 0) { //the client has disconnected server break; } //message has been received asciiencoding encoder = new asciiencoding(); bufferincmessage = encoder.getstring(message, 0, bytesread); if (system.text.regularexpressions.regex.ismatch(bufferincmessage, properties.settings.default.reqlogin, system.text.regularexpressions.regexoptions.ignorecase)) { bufferincmessageresult = bufferincmessage.split('^'); nickname_cl = bufferincmessageresult[1]; password_cl = bufferincmessageresult[2]; getuserdata_db(); login(); byte[] buffer = encoder.getbytes(inlogmessage); clientstream.write(buffer, 0, buffer.length); clientstream.flush(); } } }
your client dispatched in different threads, not intersect. need add "dispatchmethod" messages processed.
using system.text.regularexpressions; ... if (regex.ismatch(bufferincmessage, properties.settings.default.reqlogin, regexoptions.ignorecase)) { ... } else if (regex.ismatch(bufferincmessage, /*some of command1*/, regexoptions.ignorecase)) { ... } else if (regex.ismatch(bufferincmessage, /*some of command1*/, regexoptions.ignorecase)) { ... }
Comments
Post a Comment