我的服务器代码是这样的:
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(host,port) 并继续我的代码。