我的服务器代码是:
import SocketServer
import json
class MyTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
class MyTCPServerHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
data = json.loads(self.request.recv(1024).strip())
# process the data, i.e. print it:
print data
# send some 'ok' back
self.request.sendall(json.dumps({'return': 'ok'}))
except Exception, e:
print "Exception wile receiving message: ", e
def socket_server(host,port):
print host,port
server = MyTCPServer((host, port), MyTCPServerHandler)
server.serve_forever()
我试图从像这样的脚本中调用它
import threading
server_thread = threading.Thread(target=socket_server, args=('127.0.0.1', 13373))
server_thread.start()
#after this i have other code..
所以当它启动服务器....并且一切都很好但不知何故..它试图再次启动相同的代码..
因为我看到了这个错误:
Exception in thread Thread-1:
Traceback (most recent call last):
127.0.0.1 13373 <---- THIS IS THE PORT WHICH IS CONNECTED
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 530, in __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 483, in run
self.__target(*self.__args, **self.__kwargs)
File "/Users/mohitdeepsingh/Desktop/project/flaskapp/app/sock_lib/sock_server.py", line 21, in socket_server
server = MyTCPServer((host, port), MyTCPServerHandler)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 408, in __init__
self.server_bind()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 419, in server_bind
self.socket.bind(self.server_address)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
error: [Errno 48] Address already in use
所以基本上我要做的就是在后台调用socket_server(主机,端口),然后继续我的代码。
答案 0 :(得分:0)
服务器关闭(或关闭)后你正在关闭(整理)吗?在运行服务器之前扫描并关闭计算机上的开放端口,例如要用于服务器的端口。
如果你没有关闭一个端口,那么在关闭或明确关闭端口之前,端口将无法使用!