0

I have been trying to do some coding with sockets recently and found out that i often get broken pipe errors, especially when working with bad connections.

In an attempt to solve this problem I made sure to sleep after every socket operation. It works but it is slow and ugly.

Is there any other way of making a socket connection more stable?

  • Can you specify more what kind of error you are getting because `broken pipe error` is not explaining much about the problem? – Vatsal Parsaniya Mar 07 '21 at 14:19
  • Well the problem is basically the server and client getting out of sync, the server (or client) receives something that should have been received already. Then either both the server and client are trying to send or the client and server are trying to receive. when both are trying to send, "broken pipe error" is the error message. – Blaise N'kufo Mar 07 '21 at 14:31

2 Answers2

1

...server and client getting out of sync

Basically you say that your application is buggy. And the way to make the connection more stable is therefor to fix these bugs, not to work around it with some explicit sleep.

While you don't show any code, a common cause of "getting out of sync" is the assumption that a send on one side is matched exactly by a recv on the other side. Another common assumption is that send will actually send all data given and recv(n) will receive exactly n bytes of data.

All of these assumptions are wrong. TCP is not a message based protocol but a byte stream. Any message semantics need to be explicitly added on top of this byte stream, for example by prefixing messages with a length or by having a unique message separator or by having a fixed message size. And the result of send and recv need to be checked to be sure that all data have been send or all expected data have been received - and if not more send or recv would need to be done until all data are processed.

Adding some sleep often seems to "fix" some of these problems by basically adding "time" as a message separator. But it is not a real fix, i.e. it affects performance but it is also not 100% reliable either.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
0

I've been using Python's Sockets for a long time and I can tell that as long as your code (which you unfortunately didn't provide) is clean and synchronized in itself you shouldn't get any problems. I use Sockets for small applications where I don't necessarily want/need to write/use an API, and it works like a dream.

As @Steffen already mentioned in his answer, TCP is not a message based protocol. It is a "stream oriented protocol" which means that is sends data byte-by-byte and not message-by-message..

Take a look at this thread and this paper to get a better understanding about the differences.

I would also suggest taking a look at this great answer to know how to sync your messages between your server and your client(s).

Murad Alm.
  • 79
  • 9