I am trying to write a TCP client-server program in Python. The server echoes back (all CAPS) whatever the client sends to the server, once a connection is established. The server should be able to handle more than one request at a time in parallel by using threads.
However, as soon as I run the server.py file, I get the error :
Only one usage of each socket address (protocol/network address/port) is normally permitted.
I have tried changing the port number, and also tried using setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
I am still getting the error. Please Help. Here is my code so far.
#!/usr/bin/python
import socket
import sys
import threading
class Server:
def __init__(self):
self.host = ''
self.port = 12345
self.backlog = 5
self.size = 1024
self.server = None
self.threads = [] #initalizes a list of client threads
def open_socket(self):
try:
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.server.bind((self.host,self.port))
self.server.listen(5)
except socket.error, (value,message):
if self.server:
self.server.close()
print "Could not open socket: " + message
sys.exit(1)
def run(self):
self.open_socket()
running = 1
while running:
# handle the server socket
c = Client(self.server.accept())
c.start()
self.threads.append(c)
#close all threads
self.server.close()
for c in self.threads:
c.join()
class Client(threading.Thread):
def __init__(self,(client,address)):
threading.Thread.__init__(self)
self.client = client
self.address = address
self.size = 1024
def run(self):
running = 1
while running:
data = client.recv(size)
if data == 'Quit':
break
else:
print 'Received : ', data
newdata = data.upper()
client.send(newdata)
print '\nConnection Closed'
client.close()
running = 0
if __name__ == "__main__":
s = Server()
s.run()