tcp - Synchronization in C# networking -
i have simple tcp server class
class server { private tcplistener tcplistener; private thread listenthread; public server() { this.tcplistener = new tcplistener(ipaddress.parse("127.0.0.1"), 3000); this.listenthread = new thread(new threadstart(listenforclients)); this.listenthread.start(); console.writeline("hello"); } private void listenforclients() { this.tcplistener.start(); while (true) { //blocks until client has connected server tcpclient client = this.tcplistener.accepttcpclient(); //create thread handle communication //with connected client thread clientthread = new thread(new parameterizedthreadstart(handleclientcomm)); console.writeline("new connexion"); clientthread.start(client); } } private void handleclientcomm(object client) { tcpclient tcpclient = (tcpclient)client; networkstream clientstream = tcpclient.getstream(); console.writeline("got stream"); byte[] message = new byte[4096]; int bytesread; console.writeline("initializing.."); while (true) { bytesread = 0; try { //blocks until client sends message console.writeline("reading.."); bytesread = clientstream.read(message, 0, 4096); console.writeline("received something"); } catch { //a socket error has occured break; } if (bytesread == 0) { //the client has disconnected server break; } //message has been received asciiencoding encoder = new asciiencoding(); console.writeline(encoder.getstring(message, 0, bytesread)); } tcpclient.close(); } }
i call in main function :
server server = new server();
and in separate client program have class
class theclient { public void connectv2() { tcpclient client = new tcpclient(); ipendpoint serverendpoint = new ipendpoint(ipaddress.parse("127.0.0.1"), 3000); client.connect(serverendpoint); networkstream clientstream = client.getstream(); asciiencoding encoder = new asciiencoding(); (int = 0; < 20; i++) { byte[] buffer = encoder.getbytes("hello server! " + i.tostring() + " "); console.writeline("processing.."); clientstream.write(buffer, 0, buffer.length); clientstream.flush(); console.writeline("hello server sent"); } } }
i call in main function like
theclient tc = new theclient(); tc.connectv2();
my problem server program seems slower client, don't react before 13th, or more, message client :
[i can't post images because of reputation]
it reads first dozen of messages in 1 go, , reads others 1 one.
and if make server emit first, client receive message, both stop, if both wait other send something.
can explain me behavior ? how can control , synchronize ?
tcp not message based. provides stream of bytes. responsibility separate messages. note, might receive part of message in 1 read
call.
here's simple way that: send messages individual lines. possibly using streamwriter
. receive messages using streamreader.readline()
.
that way can use more sane encoding such encoding.utf8
.
besides code fine , workable. extremely rare see working tcp code on stack overflow. code horribly broken. congratulations.