Python: [socket] A simple TCP client

Articles may may have files attached at the end of the post

This article will show how to connect to a remove TCP server using python's socket module.

In this tutorial, we are going to connect to a server, send some data and then read from the socket.

As an example, we are going to write a small script that will connect to coding.debuntu.org on port 80 and request the rss file: /rss.xml.
The server will then return the HTTP reply to the request, containing the HTTP headers and the HTTP message content.

Below is the script used:

  1. #!/usr/bin/env python
  2.  
  3.  
  4. import sys
  5.  
  6. HOST = 'coding.debuntu.org'
  7. GET = '/rss.xml'
  8. PORT = 80
  9.  
  10. try:
  11.   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  12. except socket.error, msg:
  13.   sys.stderr.write("[ERROR] %s\n" % msg[1])
  14.   sys.exit(1)
  15.  
  16. try:
  17.   sock.connect((HOST, PORT))
  18. except socket.error, msg:
  19.   sys.stderr.write("[ERROR] %s\n" % msg[1])
  20.   sys.exit(2)
  21.  
  22. sock.send("GET %s HTTP/1.0\r\nHost: %s\r\n\r\n" % (GET, HOST))
  23.  
  24. data = sock.recv(1024)
  25. string = ""
  26. while len(data):
  27.   string = string + data
  28.   data = sock.recv(1024)
  29. sock.close()
  30.  
  31. print string
  32.  
  33. sys.exit(0)

Executing this script will produce:

./socket_client.py  
HTTP/1.1 200 OK
Date: Thu, 05 Jun 2008 19:22:34 GMT
Server: Apache
Set-Cookie: SESS25b075688450425d14146275d5eee6c2=30f08bf3bc69bfc905708aa7e4321c6b;
 expires=Sat, 28 Jun 2008 22:55:54 GMT; path=/; domain=.coding.debuntu.org
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified: Thu, 05 Jun 2008 19:22:34 GMT
Cache-Control: store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Connection: close
Content-Type: application/rss+xml; charset=utf-8

rss data.......

AttachmentSize
socket_client.py.txt580 bytes