c# - Client not receiving message in time (TcpClient) -
i have 2 applications "talk" each other tcp, problem when send something, application doesn't receives @ same time, when requests second time, 'he' receives duplicated. example:
client request connection (income string: 00200001 0050);
server accept connection(acknowledge) (output string: 00570002);
the client doesn't receives acknowledge, when requests connection again, receives output string of: 00570002 00570002 (duplicated).
this happens in application connects mine.
private int listenerport = 4545; private tcplistener listener; private tcpclient socket; public communicator() { try { this.listener = new tcplistener(ipaddress.parse("127.0.0.1"), listenerport); listenerport++; listener.start(); this.connecttopendingrequest(); } catch (exception ex) { listener.stop(); throw new exception(ex.message); } } /// <summary> /// try connect pending requests /// </summary> public void connecttopendingrequest() { try { if (socket == null || !socket.connected) if (listener.pending()) { this.socket = listener.accepttcpclient(); this.socket.nodelay = true; } } catch (invalidoperationexception) { throw new exception("listener not started!"); } catch (exception ex) { throw new exception("error has ocurred when connecting device: " + ex.message); } } /// <summary> /// send messages device /// </summary> public void sendmessages(string stringmessage) { if (socket.connected) { try { byte[] outstream = encoding.ascii.getbytes(stringmessage); socket.getstream().write(outstream, 0, outstream.length); socket.getstream().flush(); } catch (exception ex) { throw new exception("message not sent.\nerror: " + ex.message); } } else { throw new exception("no device connected"); } } /// <summary> /// message socket /// </summary> /// <returns></returns> public string getmessagefromsocket() { try { byte[] instream = new byte[10025]; socket.getstream().read(instream, 0, (int)socket.receivebuffersize); return system.text.encoding.ascii.getstring(instream); } catch (exception ex) { throw new exception("message not read.\nerror: " + ex.message); } } am forgetting something? have way ensure message has arrived ? (guess tcp should but...)
ps: don't have issues when receiving messages.
thanks in advance!
listenerport++;not needed. several clients can connect same listener on same port- i don't see client code here or entangled server code
- socket.getstream().flush() not needed.
- .pending() non-blocking can miss moment of connection
- look @ tcplistener , tcpclient code samples
Comments
Post a Comment