BYUBRIGHAM YOUNG UNIVERSITY
Computer Science
Python Network Programming

The Socket Module

A Simple Echo Client

Here is an echo client that will talk to our echo server (echoclient-simple.py):

#!/usr/bin/env python

"""
A simple echo client
"""

import socket

host = 'localhost'
port = 50000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send('Hello, world')
data = s.recv(size)
s.close()
print 'Received:', data

Let's go through this code a few lines at a time:


import socket

host = 'localhost'
port = 50000

As with the server, the client must import the socket module and set the host name and port number variables. The client, however, must use the name of the server it will contact. Note that these should be passed on the command line; we will discuss argument parsing later.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

This creates a socket. Note that the client uses the same syntax as for the server.

s.connect((HOST, PORT))

The client uses the connect() method to connect to the server. This must be issued after the server has called accept(), or else the connect will fail. You should check for exceptions when calling this and other socket methods.

s.send('Hello, world')
data = s.recv(size)

The send() method transmits data to the server. As with the server, the client should check the return value to determine how much data was actually sent. The client uses the recv() method to get data back from the server, specifying a buffer size to indicate the maximum amount of data it will handle at a time. Again, the data received may be less than this maximum.

s.close()
print 'Received:', data

These lines close the socket and print out the data that was received.