First of all, I am sorry that I cannot give you a minimal example. The code started to become very complex and I don't think I can prepare one anymore.
but if I were to tell you simply what I'm doing, this code allows me to communicate between the application I wrote and another external application via socket programming.
I send a file path to this external program and it adds this path to its own settings.
The weird thing is that if I send a message (i.e. the file path) for the first time, there is no problem. But when I send it for the second time, the external application does not receive the message (and I don't get any errors). Things start to get even weirder at this point because if I send a message for the third time, this time it gets the message / file path I sent for the second time to its own settings.
Example case:
sent message: A
message received: A
sent message: B
message received: (message not received)
sent message: B
message received: B
sent message : C
message received: (message not received)
sent message: C
message received: (message not received)
sent message: C
message received: C
.
.
.
("message not received" keeps increasing)
The functions I used:
def send_message(socket: QTcpSocket, message: str = "", message_type: str = "message"):
socket_stream = QDataStream(socket)
socket_stream.setVersion(QDataStream.Qt_5_10)
header_array = QByteArray()
message_size = len(message.encode("utf-8"))
header = f"messageType:{message_type},messageSize:{message_size},"
header_array.prepend(header.encode("utf-8"))
header_array.resize(128)
byte_array = QByteArray(message.encode("utf-8"))
byte_array.prepend(header_array)
socket_stream << byte_array
socket_stream.writeString(message)
def read_socket(self):
buffer = QByteArray()
socket_stream = QDataStream(self.socket)
socket_stream.setVersion(QDataStream.Qt_5_10)
socket_stream.startTransaction()
socket_stream >> buffer
header = buffer.mid(0, 128)
...
message = socket_stream.readString()
What kind of situations can cause this problem?
CodePudding user response:
You MUST REMEMBER that TCP is not a packet protocol -- it is a streaming protocol. You will NOT get packets in exactly the same shape they were sent. If you send 40 bytes and 80 bytes quickly, the other end is probably going to get a single read of 120 bytes. Or, it might get 20 bytes then 60 bytes then 40 bytes. There are no guarantees. You MUST be able to handle multiple messages in a single read, and you MUST have a way to detect when your message is finished.