0

我的服务器代码是这样的:

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) 并继续我的代码。

4

1 回答 1

0

服务器关闭(或关闭)后您是否正在关闭(整理)?在运行服务器之前扫描并关闭您机器上的开放端口,即您打算用于服务器的端口。

如果您不关闭端口,则该端口将无法使用,直到关闭或明确关闭端口!

于 2013-02-12T11:01:26.073 回答