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:

PYTHON:
  1. try:
  2.     host = "example.com"
  3.     port = 80
  4.     # Create a socket object:
  5.     s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
  6.     # If any operation takes more than 2 seconds, drop to the "except" below
  7.     s.settimeout( 2 )
  8.     # Connect to the host
  9.     s.connect( ( host, port ) )
  10.     # Send "Some string\n" to the host
  11.     s.send( "Some string\n" )
  12.     # See if the host has anything to say in reply
  13.     response_string, server = s.recvfrom(4096)
  14.    # Print the response
  15.     print response_string
  16.  
  17. except socket.error, msg:
  18.    # If anything bad happened above, this runs:
  19.    print "An error occurred:", msg
  20.  
  21. else:
  22.    # If all went well (no exceptions), we get here:
  23.    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.

One Response to “Python Sockets: Clean, Concise”

  1. paul Says:

    very nice, that worked immediately.

    now to implement it on the localhost ^.^

Leave a Reply