Reputation: 152
I have a Python socket established in my server.py file and a client that connects to it in my client.py file. It worked fine the first I ran both scripts in my command line but now every time I run them I get:
OSError: [Errno 48] Address is already in use
but the server.py file still seems to run just fine even with that error. However my client.py file is not receiving a message that I am trying to send.
#server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f'Connection from {address} has been established.')
#this prints as expected
clientsocket.send(bytes("Test Message", "utf-8"))
My print statement works just fine even though I receive the Address is already in use error
.
#client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 1234))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Nothing is printing from my client.py file so I assume that it is not receiving the message. I suspect that it is caused by the error that it is giving but I am unsure how to fix it.
What is the best way to close all of the current connections? Also, is this related to the connections already being opened? Is there a way to be certain that the message is being sent and that my client is receiving it? Below is how I am running the scripts if it is relevant.
python3 server.py & python3 client.py
Upvotes: 0
Views: 1360
Reputation: 6908
In server.py
, immediately after you create the socket, try adding:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
The SOL_SOCKET
option specifies that the setting applies to the socket API in a protocol-independent manner, as opposed to a specific protocol, such as TCP. The SO_REUSEADDR
option with the value of 1
enables the address to be re-used as long as the socket is in TIME_WAIT
state, meaning that it has been closed, but is being held for a short while to allow any remaining packets to arrive and be identified with that connection. If the socket is in any other active state, you will still get the address already in use
error.
This isn't a cure-all for all socket issues, but it may allow the server to re-bind to the port if it's spending too long in TIME_WAIT
status.
Upvotes: 1
Reputation: 51
Both the files are working fine for me.
Try using another port instead of 1234
Upvotes: 0