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

출처 - http://coding.debuntu.org/python-socket-simple-tcp-client



Posted by linuxism
,