Python socket server failing

I'm trying to start a UDP server in python 3.

I copied the code from this example.

This is my exact code.

import socketserver

class MyUDPHandler(socketserver.BaseRequestHandler):
    """
    This class works similar to the TCP handler class, except that
    self.request consists of a pair of data and client socket, and since
    there is no connection the client address must be given explicitly
    when sending data back via sendto().
    """

    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]
        print("{} wrote:".format(self.client_address[0]))
        print(data)

if __name__ == "__main__":
    HOST, PORT = "localhost", 19446
    with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
        server.serve_forever()

I have only removed the reply from the handle method and changed the port number.

when i try to run it i get this

$ sudo python3 test.py
  File "test.py", line 19, in <module>
    with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
AttributeError: __exit__

I am attempting to run this in Python 3.4.2 installed on a Raspberry Pi 3, it was working this morning. I googled AttributeError: __exit__ and found that with uses built in methods such as __exit__ to gracefully close after it has finished running instructions indented after it.

The exact same code runs fine on my windows machine (Python 3.6.2) and the code used to run on my raspberry pi and the only thing i have done with it all day was install x11vnc server and plugged in a lot of USB devices. (A capture card and arduinos, no usb drives from untrusted sources).

So my question is, what can cause an Attribute Error: __exit__ in the socketserver library.

Upvotes: 4

Views: 1312

Answers (1)

georgexsh
georgexsh

Reputation: 16624

context manager was added to socketserver in 3.6: https://bugs.python.org/issue26404, with commit.

below 3.6, in 3.4.2, you have to call server_close() manually:

try:
    server = socketserver.UDPServer((HOST, PORT), MyUDPHandler)
    server.serve_forever()
finally:
    server.server_close()

Upvotes: 3

Related Questions