2011-04-02 127 views
2

我正在Python 3.1中運行使用socketserver模塊的Python服務器。每次我從客戶端獲得連接(客戶端成功連接)時,我的服務器都會收到錯誤消息。這裏是我的代碼:連接時發生Python SocketServer錯誤

import socket 
import socketserver 
import string 
import struct 

class Server(socketserver.BaseRequestHandler): 
    def __init__(self): 
     self.address = self.client_address[0] 
     print("%s connected." % str(self.address[1])) 
    def handle(self): 
     message = self.request.recv(1024).decode().strip() 
     print("%s sent: '%s'" % (self.address,message)) 

if __name__ == "__main__": 
    server = socketserver.TCPServer(("localhost",22085), Server) 
    print("Socket created. . .") 
    print("Awaiting connections. . .") 
    server.serve_forever() 

這裏是我的錯誤:

---------------------------------------- 
Exception happened during processing of request from ('127.0.0.1', 49669) 
---------------------------------------- 
Traceback (most recent call last): 
    File "C:\Python31\lib\socketserver.py", line 281, in _handle_request_noblock 
    self.process_request(request, client_address) 
    File "C:\Python31\lib\socketserver.py", line 307, in process_request 
    self.finish_request(request, client_address) 
    File "C:\Python31\lib\socketserver.py", line 320, in finish_request 
    self.RequestHandlerClass(request, client_address, self) 
TypeError: __init__() takes exactly 1 positional argument (4 given) 

我注意到了有關錯誤的奇怪的是,它提供了有關第二行中的端口是不是我的端口不同使用。我不確定這裏的錯誤是什麼......

感謝您的幫助。

回答

3

嘗試調用父類的方法__init__

class Server(socketserver.BaseRequestHandler): 
    def __init__(self): 
     self.address = self.client_address[0] 
     print("%s connected." % str(self.address[1])) 
     super(Server,self).__init__()     # Init your base class 
+0

感謝@Adam!我沒有意識到我正在覆蓋__init__方法。我會接受你的評論作爲最好的一次stackoverflow允許我。但是,我仍然收到錯誤,因爲它需要多個參數......有沒有什麼辦法可以在創建對象時不調用我的代碼而不覆蓋現有的構造函數? – pajm 2011-04-02 21:24:50

+0

嘗試刪除'decode()',將其保留爲'self.data = self.request.recv(1024).strip()'。看到這裏:http://docs.python.org/release/3.1.3/library/socketserver.html#module-socketserver – 2011-04-02 22:00:31

相關問題