Python SocketServer error upon connection
I am running a Python server using the socketserver
module in Python 3.1. Every time I get a connection from the client (which succeeds client side), my server receives an error. Here is my code:
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开发者_StackOverflow社区__":
server = socketserver.TCPServer(("localhost",22085), Server)
print("Socket created. . .")
print("Awaiting connections. . .")
server.serve_forever()
And here is my error:
----------------------------------------
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)
The odd thing I noticed about the error is that the port it gives on the second line is different than the port I'm using. I'm not really sure what the error is here...
Thanks for the help.
Try calling the __init__
method of the superclass:
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
Almost a decade later, I had the same problem. (Python 3.9)
Thanks to the voted answer above as guidance, I was able to find out that the Customised RequestHandler is expected to take 3 arguments, so I had to override a 3-parameter __init__
as follows to resolve the errors.
class ServerRequestHandler(socketserver.BaseRequestHandler):
def __init__(self, request, client_addr, server):
# Custom initialisation code here....
super().__init__(request, client_addr, server)
精彩评论