2012-07-02 22 views
2

包括下面是我目前使用的代码:Python的SocketServer的工作在本地主机,但不能在服务器

#! /usr/bin/python 
print 'Content-type: application' 
print '\n\n' 

import SocketServer 
import cgitb 
cgitb.enable() 

class MyTCPHandler(SocketServer.BaseRequestHandler): 
    """ 
    The RequestHandler class for our server. 

    It is instantiated once per connection to the server, and must 
    override the handle() method to implement communication to the 
    client. 
    """ 

    def handle(self): 
     # self.request is the TCP socket connected to the client 
     self.data = self.request.recv(1024).strip() 
     print "{} wrote:".format(self.client_address[0]) 
     print self.data 
     # just send back the same data, but upper-cased 
     self.request.sendall(self.data.upper()) 
     self.request.sendall('Data Received') 

if __name__ == "__main__": 
    HOST, PORT = "localhost", 9989 

    # Create the server, binding to localhost on port 9989 
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) 

    # Activate the server; this will keep running until you 
    # interrupt the program with Ctrl-C 
    server.serve_forever() 

代码工作在本地主机上如预期,但公共服务器上反应迟钝。

此外,执行了两次代码将导致以下错误信息:

error: (98, 'Address already in use')

回答

4

error: (98, 'Address already in use')

你需要这个为:

socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 

but is unresponsive on public server.

通常的情况下,共享主机,你不能通过创建一个套接字。在任何情况下,你可以尝试以下方法,来看看是否有帮助:

HOST, PORT = "", 9989 # or (public_IP,9989) 
-1

你不能运行它两次,因为你有一个静态端口地址(9989)。只能有一个监听器绑定到一个端口。可以有多个到该端口的传入连接,但只能有一个侦听器。

此外,你检查了防火墙设置。无论您的python服务器在哪里运行,防火墙都必须授予端口9989的权限才能接受传入连接。另外,如果您的服务器位于集线器后面,则必须告知集线器哪个主机要处理端口9989.

+0

他在第一次死亡后第二次运行**。 – SuperSaiyan

5

我认为问题在于您绑定了"localhost",即在回送接口上。尝试用您想要绑定的公共IP地址替换"localhost"。如果您不确定它是什么,请在命令行键入ifconfig;选择不在私人使用的任何IP块中的地址(即,不以10或192.168等开始)。

我不确定它是否可以专门与TCPServer协同工作,但通常需要绑定到特定接口的软件才会接受所有接口的"0.0.0.0",或者使用空字符串来达到相同的效果。

0

你必须gethostbyname()功能使用"localhost"

server = SocketServer.TCPServer((socket.gethostbyname(HOST), PORT), MyTCPHandler)

但你要记住,有些机器不明白"localhost",你必须使用本地主机的IP地址,而不是127.0.0.1

相关问题