c# - .NET Help using TCP classes -


i'm trying learn network programming , i'm trying create tcp server , tcp client.

the server start , listen connections. client connect , send string server. server reply string containing received string.

the issue i'm facing first try works after client receive empty reply.

below code server:

public void handlerthread() {  tcpclient tcpclient = clients[clients.count - 1];   networkstream networkstream = tcpclient.getstream();  int = -1;  while (tcpclient.connected )  {   byte[] data = new byte[1024];   if ((i=networkstream.read(data, 0, data.length)) != 0)   {    string incomingmessage = encoding.ascii.getstring(data);    debug.writeline("ddb server incomingmessage: " + incomingmessage);    this.invoke((methodinvoker)(() => lbmessage.items.add("message received is: " + incomingmessage)));    // send response.    data = new byte[1024];    string outmessage = string.empty;    outmessage = "recieved msg: " + incomingmessage;    data = system.text.encoding.ascii.getbytes(outmessage);    networkstream.write(data, 0, data.length);    debug.writeline("ddb server reply: " + outmessage);    this.invoke((methodinvoker)(() => lblstatus.text = "sent reply!"));   }  } } 

the client's code:

private void button2_click(object sender, eventargs e) {  if (!string.isnullorempty(_txtboxmsg.text))  {   try   {    byte[] data = system.text.encoding.ascii.getbytes(_txtboxmsg.text);    stream = client.getstream();    // send message connected tcpserver.     stream.write(data, 0, data.length);    debug.writeline("ddb client message: " + _txtboxmsg.text);    data = new byte[1024];    string responsedata = string.empty;    int32 bytes = stream.read(data, 0, data.length);    responsedata = system.text.encoding.ascii.getstring(data, 0, bytes);    debug.writeline("ddb client recieved: " + responsedata);    lbmsgs.items.add(string.format("received: {0}", responsedata));   }   catch (argumentnullexception ex)   {    messagebox.show("argumentnullexception: " + ex); ;   }   catch (socketexception ex)   {    messagebox.show("socketexception: " + ex);   }  }  else   messagebox.show("you did not enter message sent server!", "please enter message", messageboxbuttons.ok); } 

i noticed while using debug.writeline() first run message displayed correctly. after messages next each other (as if using debug.write()). behavior byte representation messages being corrupted (for example return character or something)?


Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -