Here is server side code:
import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 7800 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print ('Socket now listening')
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
msg = conn.recv(1024)
s.close()
whenever I use this code for the first time I can easily connect with the client and after second time I get the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"
How could I modify the code that it will work again and again?
Try this line after creating s :
# ...
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# ...
Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With