Michael Michael - 1 year ago 210
Python Question

Multithreaded webserver in Python

An example from a video lecture. Background: the lecturer gave a simplest web server in python. He created a socket, binded it, made listening, accepted a connection, received data, and send it back to the client in uppercase. Then he said that there is a drawback: this web server is single-threaded. Then let's fork.

I can't understand the example well enough. But to start with, the program exits (sys.exit()). But I can't run it again:

socket.error: [Errno 98] Address already in use.

I try to find out which process is listening on port 8080: netstat --listen | grep 8080. Nothing.

Well, what is listening on 8080? And how to kill it?

Added later:
There is a feeling that if I wait for some time (say, 5-10 minutes), I can run the program again.

import os
import socket
import sys

server_socket = socket.socket()
server_socket.bind(('', 8080))
print "Listening"

while True:
client_socket, remote_address = server_socket.accept()
print "PID: {}".format(os.getpid())
child_pid = os.fork()
print "child_pid {}".format(child_pid)

if child_pid == 0:
request = client_socket.recv(1024)
print '(child {}): {}'.format(client_socket.getpeername(), request)


Answer Source

The correct netstat usage is:

netstat -tanp

because you need the -a option to display listening sockets. Add grep to locate your program quickly:

netstat -tanp| grep 8080
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download