pythonsocketsunix-socket

Is it possible to send data continuously to a unix domain socket without any reading counterpart?


I need to connect two processes with unix sockets: a producer that streams a video, a consumer that should read the video and process it.

As the video stream comes from a live stream, I initially thought of continuously writing data to the socket with the producer process, then the consumer would start to consume it when ready.

However I was not able to implement this behavior with AF_UNIX sockets, as I was not able to start the sender before the receiving socket exists. Can this actually be implemented?

This non-blocking send behavior I thought of can be achieved with AF_INET sockets (that is, UDP communication), where the producer can write continuously, and the reader starts to consume as it sees fit. Here is the sample python code for this feature: the sender can be started and it will start to send messages right away; the receiver can then be started when needed.

# sender.py
import socket
import time

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)

try:
    # Send data
    i = 0
    while True:
        msg = f"message: {i}"
        sent = sock.sendto(bytes(msg, encoding="ascii"), server_address)
        print(f"sent {sent} bytes - {msg}")
        i += 1
        time.sleep(0.05)

finally:
    print('closing socket')
    sock.close()

# receiver.py
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)

sock.bind(server_address)

try:
    while True:
        data, address = sock.recvfrom(4 * 1024)
        print(f"received {data}")
except KeyboardInterrupt:
    pass
finally:
    sock.close()


Solution

  • UNIX domain sockets are reliable sockets, even with SOCK_DGRAM. This reliability can only be achieved if there is actually somebody reading at the other end.

    Contrary to this UDP is fire and forget, i.e. does not care about successful delivery, message order or duplicated messages.