I'm currently trying to understand sockets in Python and I'm using the following code to receive data transmitted via TCP from a Smartphone on a Hotspot network.
import socket
import logging
# Logging routine
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 5000)
logger.info('starting up on %s port %s' % server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
# Wait for a connection
logger.info('waiting for a connection')
connection, client_address = sock.accept()
try:
logger.info('connection from', client_address)
while True:
data = connection.recv(16)
if data:
print 'Do stuff here'
else:
print 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
The first time I run the code everything works correctly. After running the script and want to run again I have the following error: [Errno 48] Address already in use?
. However, if I run the script again after the program crashes, it all works correctly. I had checked and confirmed that it ends on the finally statement for connection.close()
. It seems that I have always to run the program two times to be able to run two consecutive times.