Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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__":
    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.

like image 476
pajm Avatar asked Apr 21 '26 16:04

pajm


2 Answers

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
like image 123
Adam Matan Avatar answered Apr 24 '26 04:04

Adam Matan


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)
like image 41
Wilson Avatar answered Apr 24 '26 05:04

Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!