1. Home
  2. Computing & Technology
  3. Python

Building a Web Client in Python

From Al Lukaszewski, for About.com

6 of 9

Connecting Sockets With Python

After creating the socket, we need to connect to it using the connect method of the socket object. The socket is essentially an opening in the networking capacity of the computer. In connecting, we give it a host and port for network communication.

c.connect((host, port))
It is worth noting that the address for the connection is given as a tuple (hence the double parentheses).

Before we can read from the socket, however, we need to make a file-like object from it. Remember, Python read and writes to file-like objects, not sockets. So, we essentially tell Python to view the socket as a file. All sockets have a function makefile that takes two arguments: the mode and the buffer size. In our case, we want a simple read mode that has no buffer.

fileobj = c.makefile('r', 0)
Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. Networking
  5. Python Programming for the Network: Connecting Sockets With Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.