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.
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
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.
This places ...