2012-07-02 41 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

相關問題