我正在尝试用Python编写TCP客户端 - 服务器程序。一旦建立连接,服务器就会回送(所有CAPS)客户端发送到服务器的任何内容。服务器应该能够使用线程并行地一次处理多个请求。
但是,只要我运行server.py文件,就会收到错误:
通常只允许使用每个套接字地址(协议/网络地址/端口)。
我尝试更改端口号,并尝试使用setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
我仍然收到错误。请帮忙。到目前为止,这是我的代码。
#!/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()
答案 0 :(得分:0)
如果您使用其他端口,错误仍然存在?如果没有,那么你的脚本仍在某处运行。