admin管理员组

文章数量:1394979

I am writing a Python 3-based server/client program using a Unix-domain socket. I am trying to build the server such that only a single client can connect to the server and subsequent connect() calls should return connection refused error until the connected client disconnects.

The client behaves exactly as expected when netcat (nc) is used as the server. But for my Python server code even accepts only a single accept() call on a socket that has been configured with listen(0). Multiple clients successfully connect without error.

Behaviour with netcat (nc):

$ nc -lU /tmp/uds0 &
[1] 387992
$ 
$ nc -U /tmp/uds0 &
[2] 388009
$     
$ nc -U /tmp/uds0
Ncat: Connection refused.

Unexpected behaviour with python code:

$ cat uds-server.py 
#! /usr/bin/python3

import socket
import os
import sys

SOCKET_PATH = "/tmp/uds0"

# Create the socket
server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

# Bind the socket to the file path
server_socket.bind(SOCKET_PATH)

# Listen - handle number of queued connections
server_socket.listen(0)

# accept a single client and proceed
(client_socket, client_address) = server_socket.accept()

print("New client connected, waiting for messages")
msg = client_socket.recv(1023)

print(msg.decode())
$ 
$ 
$ ./uds-server.py &
[5] 388954
$ 
$ nc -U /tmp/uds0 &
[6] 389017
$ New client connected, waiting for messages

$ 
$ nc -U /tmp/uds0

How can I make the Python server behave the same way as netcat?

本文标签: