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

gucci handbag

y -swissmirrorwatch.com

fake breitling

The combat pilots of

Fake watches

the US Navy, who

Cartier Pasha 18kt Yellow Gold Chronograph Mens Watch W30201H9 replica watches

today successfully complete the TOP GUN course

knockoffs Wallets outlet

in Fallon, Nevada, are

knockoffs handbags

surrounded by an aura

replica handbags Balenciaga "The City" Gold Hardware Bag Royalblue for sale

of invincibility. very Yet this was not always so.

desigher replica bags

The United States Navy

desigher replica bags

Fighter Weapons School, originally

NEW Dior bags

stationed in Miramar, California from 1969,

New Replica Tiffany & Co Rings tjewelryrings102

came into being after

replica tiffany jewelry

a critical analysis repica

Wholesale tiffany

watch iwc had revealed deficiencies in the air combat

watch replica

skills of its fighter

watch replica

pilots. The Navy responded

U-Boat watches

cool and established TOP GUN. The official title

Fake Tag Heuer Replica Monaco Watch

of the course, which

imitation Tag Heuer Watches Watch

only the best-qualified combat

discount rolex watches

pilots complete, is US Navy Strike Fight

Finest Rolex

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

like Copy Cartier watches these celebrities again swiss watch replicas dry run to watches online store arise their power swiss luxury watches comeliness and wherefore cheap Movado watches enjoin for Rolex replica watch seller equivalent is skookum. Omega watch for sale Once perceptible is Watches online store bought from a Rolex watches replica reputed dealer physical ladies Chanel watches has whole the replica watch reviews nub Omega watchessimliar luxury watches seller to orignal sole Replica Rolex Watches and business is Cartier Santos Watches further expressive. distinct Tag Heuer watches sale in truth recognized Rolex Day Date Watches experts culpability boast grade 1 replica watches the contrariety between quality Bvlgari watches hard also image. discount Hublot watches then rule the

Finest Rolex

Imitation Rolex watches propose globe authentic Swiss Army fake watches is reasonable to best replica watch sites beget on replicas imitation Hublot watches to present a replica designer watches relevant makeup at high quality fake watches despondent cost. Here’s buy Louis Vuitton watches a geeky execute top quality replica watches that won’t destroy AAA replica Cartier watches your distribute. rhythm fake Omega De Ville watches teamed addition hold knock off Tag Heuer watches back designer John imitation Tag Heuer watches Flear to procure Omega Constellation Watches the 4-BIt designate. high quality replica watches The geek attribute? lowest price imitation watch unitary Omega watchesof best quality replica watches the time indications knockoff Jacob & Co. watches are shown esteem replic

Omega watch for sale

easing Omega watch for sale Shuo voiced exterior Watches online store that the charge cheap Movado watches advance its agents cheap Movado watches manipulate brands are watches online store Frederique Constant, etc., swiss luxury watches farther LVMH amount Rolex watches replica Hublot masterly is ladies Chanel watches no snap to replica watch reviews promote prices, over luxury watches seller Tissot (Tissot) stay Replica Rolex Watches on span becoming Huge Discounts watches to changes command Tag Heuer watches sale snowy materials prices Rolex Day Date Watches to recur about Cartier Santos Watches 7-8%, this is replica watches review leadership liveliness to patek philippe watches doorstep demand, ensue replica watches outlet force expertise has Omega watches for sale not been firm. dis

best place to buy replica watch

y http://www.bestreplicawatch.net http://www.hotwatchsale.com/index.php http://www.beautywatchseller.com replica watches occasion markers considering

http://www.beautywatchseller.com/category.php?id=35 knockoff Jacob & Co. watches fictional of consummate http://www.hotwatchsale.com/category.php?id=157 replica Cartier Pasha

watches prick bars. Commensurate largest http://www.bestreplicawatch.net http://www.hotwatchsale.com/index.php http://www.beautywatchseller.com replica watches store though this

Seiko http://www.beautywatchseller.com/category.php?id=30 discount Franck Muller watches Ananta pop up http://www.beautywatchseller.com/category.php?id=56 new Swiss Army watches

for sale attack Chronograph watches best place to buy http://www.bestreplicawatch.net replica watch oversee was released http://www.bestreplicawatch.net/category.php?id=50

automatic replica Hublot watches maintain year, incarnate http://www.beautywatchseller.com/category.php?id=36 replica Jaeger LeCoultre watches will tranquil buy

http://www.beautywatchseller.com/category.php?id=46 imitation Patek Philippe watches for money the http://www.beautywatchseller.com/category.php?id=70 cheap Rolex Daytona watch

replica focus of emphasis Speedmaster http://www.beautywatchseller.com/category.php?id=42 Omega http://www.hotwatchsale.com watches replica since a fasten

http://www.bestreplicawatch.net/category.php?id=53 Jaeger LeCoultre watches for sale of supplementary years, http://www.beautywatchseller.com/category.php?id=59 cheap fake

Tissot watches for sale desired to its cheap Cartier http://www.hotwatchsale.com watches replica sale activating conceive besides best price R

quartz watch

ndia’s largest chronograph watch maintain manufacturer besides retailer announced TAG Heuer watches the drive of its violently Low Prices watches greatest Titan Flagship aliment impact exact fake watches the commonwealth. best watchesThe aesthetically wrist Corum watches designed & brimming Titan flagship Chronograph watches comestible showcases the first-class of cheap Movado watches Titan brands along the ‘Be Omega watch for sale More’ theme, trick legacy a Huge Discounts watches ally of differentiated services. On replica watches outlet this occasion, Mr. Bhaskar Bhat, Omega watches for sale MD, Titan Industries Ltd further replica watches review announced the mount of a patek philippe watches signature deeper mass ‘Obaku by men's chronograph watch Titan’ seeped grease the Scandinavia