Socket in Unix/Linux

Socket Server/Client in Python


Socket with Multiple Process/Threadings in Python

Theading is a standard in Unix/Linux. Each thread has its own runtime context with register data, allowing it to know which line of code need to be run. While code is actually the shared data in the process’s memory as multiple thread in a single process can share the memory.

Real Example

import socket
import threading
import time

response = 'HTTP/1.1 200 OK\r\nConnection: Close\r\nContent-Length: 11\r\n\r\nHello world'
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('', 1234))

def handler():
    while True:
        client, _ = server.accept()
        request = client.recv(1024)
        # pretent to prepare

thread1 = threading.Thread(target=handler)
thread1.daemon = True
thread2 = threading.Thread(target=handler)
thread2.daemon = True

thread1.join() # wait threading return before exit

Run by python3

Open another two windows to see the Sockets status,

Use telnet as the client to connect to our Python server,

telnet localhost 1234
Connected to localhost.
Escape character is '^]'.
abc # random input
Bye # the response from server
Connection closed by foreign host.

netstat -lt is always showing:

tcp        0      0 *:1234                  *:*		LISTEN

But netstat -t is interesting:

Every 1.0s: netstat -t                                                  

Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:1234          localhost:50688         TIME_WAIT
tcp        0      0 localhost:1234          localhost:50690         TIME_WAIT
tcp        0      0 localhost:1234          localhost:50692         ESTABLISHED
tcp        0      0 localhost:50692         localhost:1234          ESTABLISHED

Since Socket is 5-tuple with

  1. source IP address
  2. source port number
  3. destination IP address
  4. destination port number
  5. protocol

So every line above is an independent socket, although there are multiple combo of proto=tcp src=localhost:1234.

TIME_WAIT are the legacies from closed Sockets. Disappeared a few seconds after the telnet client closed.

We can create multiple connection by start multiple telnet. Each client-server connection will create a pair of,

tcp localhost:<random_port_A>   localhost:1234              ESTABLISHED
tcp localhost:1234              localhost:<random_port_A>   ESTABLISHED


  1. linux - Can I call accept() for one socket from several threads simultaneously? - Stack Overflow
  2. Socket Programming HOWTO — Python 3.8.4 documentation
  3. Understand web server concurrency models with examples in Python | Junchao’s blog
  4. concurrency - Is there a way for multiple processes to share a listening socket? - Stack Overflow
  5. linux - Calling accept() from multiple threads - Stack Overflow
  6. socket(2) - Linux manual page