Search code examples
pythontcpserver

TCP/IP Server finally: invalid syntax


I am working on a project and I just want to get the basics down of a TCP/IP server I am following an example from this website: https://pymotw.com/2/socket/tcp.html the following code is identical as far as I know.

while True:
     print >>sys.stderr, 'waiting for a connection'
     connection, client_address = sock.accept()
     try:
         print >>sys.stderr, 'client connected:', client_address
         while True:
             data = connection.recv(16)
             print >>sys.stderr, 'received "%s"' % data
             if data:
                 connection.sendall(data)
             else:
                 break
         finally:
             connection.close()

However when i try to compile this code, the error i get is:

File "server.py", line 26
  finally:
        ^

SyntaxError: invalid syntax

I do not have much experience with python so i am unsure what is happening here, any help would be appreciated


Solution

  • finally can only be paired up with try.

    Currently your indentation has it matching up with your while. Try deindenting so that it's the same indentation as your try.