Reputation: 19
I am running this on a local host and keep getting OSError: [Errno 98] Address already in use
after closing the connection and trying to run it again.
### server ###
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port= 9876
serversocket.bind((host, port))
serversocket.listen(5)
while True:
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
msg = 'Thank you for connecting'+ "\r\n"
clientsocket.send(msg.encode('ascii'))
clientsocket.close()
### client ###
import socket
sock= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9876
sock.connect((host, port))
msg = sock.recv(1024)
sock.close()
print (msg.decode('ascii'))
Upvotes: 0
Views: 1370
Reputation: 262
You must use the following statement before using the bind() method
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
If you still have problems, you can look at your network connections and close the one you used previously manually, for when you run the program again, if you have already put the above-mentioned instruction before the bind() method everything should be fine.
Upvotes: 1