7

I try to run example from : https://docs.python.org/3/library/socketserver.html#socketserver-tcpserver-example in my laptop but it didn't work.

Server :

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler 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())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()

Client :

import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data + "\n", "utf-8"))

    # Receive data from the server and shut down
    received = str(sock.recv(1024), "utf-8")

print("Sent:     {}".format(data))
print("Received: {}".format(received))

This error is showing on both client and server site :

Traceback (most recent call last):
  File "C:\Users\Win7_Lab\Desktop\testcl.py", line 8, in <module>
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
AttributeError: __exit__
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "C:\Users\Win7_Lab\Desktop\testcl.py"]
[dir: C:\Users\Win7_Lab\Desktop]
[path: C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]
Park Yo Jin
  • 331
  • 1
  • 3
  • 15
  • 1
    Possible duplicate of [How to use socket in Python as a context manager?](https://stackoverflow.com/questions/16772465/how-to-use-socket-in-python-as-a-context-manager) – Bailey Parker Mar 25 '18 at 03:37
  • 4
    You're looking at the python3 documentation, in python2 `TCPServer` does not have the context manager protocol – anthony sottile Mar 25 '18 at 03:37

1 Answers1

7

It looks like the example you're trying to run is for Python 3, while the version you're running is Python 2.7. In particular, support for using a context manager (i.e. with socket.socket()) was added in Python 3.2.

Changed in version 3.2: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling close().

If you don't want to upgrade, you should be able to modify your code by removing the with statements and calling close(), perhaps using a try statement:

try:
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
except:
    pass
finally:
    server.close()

Related to this question.

Tahlor
  • 1,642
  • 1
  • 17
  • 21