O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Simple Socket Server

The following function implements a short socket server:

# socketserver1.py - runs forever,
# reverse each message received.
from socket import *
import string

HOST = ''     # this means local
PORT = 8578   #arbitrary, high number

def serve():
    # this reverses each message received, lasts forever
    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.bind((HOST, PORT))
    serversock.listen(1)   # max bcklog of 1-5 connections
    print 'socket listening for connections...'
    while 1:
        handlersock, addr = serversock.accept()  

        # now do something with the handler socket
        print 'handler connected by', addr
        data = handlersock.recv(1024)
        print 'received', data
        handlersock.send(string.upper(data))
        handlersock.close()
        print 'handler closed'

if __name__ == '__main__':
    serve()

You can start this server by running it from a DOS prompt. Let’s step through a line at a time:

serversock = socket(AF_INET, SOCK_STREAM)

This creates the server socket. Don’t worry about the constants; there are other types of sockets, but their use is unusual and definitely out of scope for this chapter.

serversock.bind(HOST, PORT)

This associates the socket with a TCP/IP hostname and port number. An empty string, the hostname (if you know it), or the result of the function gethostname() all mean the local machine. PORT is a number between and 65535 and can be thought of like a radio channel or telephone line. The lower port numbers are used for standard services, so pick a big one.

serversock.listen(1)

This places ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required