'Address already in use' when using socket

Bearish upperbear at gto.net
Thu Apr 7 17:38:19 EDT 2005


I get 'Address already in use' errors when using sockets.
Am I properly shutting down all connections? What am I doing wrong?
I've looked at the examples and I can't figure out what I'm missing.
I already read the Python Socket HOWTO at
http://py-howto.sourceforge.net/sockets/sockets.html
but I seem to be doing everything right.

Here is the server:

#! /usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 52340))
s.listen(1)
conn, addr = s.accept()
data = conn.recv(1024)
print "data:", data
conn.close()
s.close()
print "server closed"

Here is the client:

#! /usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 52340))
s.send('test string')
s.close()
print "client closed"

Here is a convenience script to run both
(although I get the same error when I run in separate shells):

#! /bin/sh
python server.py &
sleep 1
python client.py

Here is the error:

--- first time, runs just fine ---
$ source ./runboth
data: test string
server closed
client closed
[1]+  Done                    python server.py
--- second time (or sometimes third time), gives error ---
$ source ./runboth
Traceback (most recent call last):
  File "server.py", line 4, in ?
    s.bind(('localhost', 52340))
  File "<string>", line 1, in bind
socket.error: (98, 'Address already in use')
[1]+  Exit 1                  python server.py
Traceback (most recent call last):
  File "client.py", line 4, in ?
    s.connect(('localhost', 52340))
  File "<string>", line 1, in connect
socket.error: (111, 'Connection refused')



More information about the Python-list mailing list