2013-02-12 97 views
0

我的服务器代码是这样的:线程调用socket库两次蟒蛇

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

你确定你不会创建线程两次(或更多)? – 2013-02-12 08:11:08

+0

@JoachimPileborg:naah ..但其余的代码是一个Web服务器..它启动另一台服务器在本地主机在不同的端口..你认为这可能是一个问题? – Fraz 2013-02-12 08:14:55

+0

@JoachimPileborg:嗨..其实在服务器代码..我写了一个单元测试,这是开始一个新的线程..所以而不是两个线程只有一个线程..但我仍然得到一个错误:(虽然端口是开放的..和代码执行就好..但它会抛出错误..任何线索? – Fraz 2013-02-12 08:24:04

回答

0

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

如果您不关闭端口,那么端口将不可用,直到关闭或明确关闭端口!