Python Sockets: Clean, Concise

I was recently pleased to find an excuse to code some Python for the first time. I am impressed. Python doesn’t feel like other programming languages. When I write Python I feel like I’m just telling the computer what to do, rather than constantly worrying about essoteric language issues. What I mean is this. While coding Java, I am constantly thinking about class design, exception handling, patterns, etc. While coding C++, I worry a lot about memory management and I spend a lot of time trying to remember funky STL APIs. However, while coding Python the other day, I almost forgot I was programming. It was like I was just telling the computer what to do, line after line. My day’s work culminated with a pleasant experience coding to the Python socket API. Read on for the details.

Coding Python client sockets is simple and intuitive. You just create a socket, set it up, connect it, and let Python’s superb exception handling take care of any problems. Like this:

    host = ""
    port = 80
    # Create a socket object:
    s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    # If any operation takes more than 2 seconds, drop to the "except" below
    s.settimeout( 2 )
    # Connect to the host
    s.connect( ( host, port ) )
    # Send "Some string\n" to the host
    s.send( "Some string\n" )
    # See if the host has anything to say in reply
    response_string, server = s.recvfrom(4096)
   # Print the response
    print response_string

except socket.error, msg:
   # If anything bad happened above, this runs:
   print "An error occurred:", msg

   # If all went well (no exceptions), we get here:
   print "Succcess!"

All told, I got a good ROI on learning Python. I had a working application, complete with error handling, in under a day with minimal code. There is a plethora of Python info on the web, and though I find its documentation site to be lacking compared to PHP’s docs, it’s pretty good.

4 comments to “Python Sockets: Clean, Concise”

You can leave a reply or Trackback this post.
  1. http://paul says: -#1

    very nice, that worked immediately.

    now to implement it on the localhost ^.^

  2. http://hector says: -#1

    Superb explanation for a newbie!


  3. But socket.error is not defined, is it?

  4. This is a 12 year old post. Python has changed a little since then.

Write a Reply or Comment

Your email address will not be published.