Home > database >  Python sockets, how to receive only last message instead of the whole pending buffer?
Python sockets, how to receive only last message instead of the whole pending buffer?

Time:12-04

I've got a server side socket that sends a message very frequently (it updates the same message with new data). The client side is processing that information as soon as the message is received.

My problem is that while the client is processing the message, the server side might have already send a few messages.

How could the client receive only the last message and drop all the pending packages?

This is the code I use for my client side. I made it non-blocking hoping it would solve my problem, but it didn't, so I don't know if it is even needed now.

import select
import socket
import time


class MyClient:
    def __init__(self):
        self.PORT = 5055
        self.SERVER = socket.gethostbyname(socket.gethostname())
        self.client = self.connect()
        self.client.setblocking(False)

    def connect(self):
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect((self.SERVER, self.PORT))

        return client


client = MyClient()

while True:
    inputs = [client.client]
    while inputs:
        readable, writable, exceptional = select.select(inputs, [], inputs, 0.5)
        for s in readable:
            data = client.client.recv(2048)
            print(data)
        time.sleep(1)

CodePudding user response:

There is no concept of a message in TCP in the first place, which also means that TCP cannot have any semantic for "last message". Instead TCP is a byte stream. One cannot rely on a 1:1 relation between a single send on one side and a single recv on the other side.

It is only possible to read data from the stream, not to skip data. Skipping data must be done by reading the data and throwing these away. To get the last message an application level protocol must first define what a message means and then the application logic must read data, detect message boundaries and then throw away all messages except the last.

  • Related