2007-08-29 21:20:38

Python and network sockets

One of the advantages to a high-level language such as Python is the ability to write fairly simple abstract code which produces a fairly complex feature set.

Sockets in Python is an excellent example. In approximately 40 lines of code, a simple client/server application can be built.

Server:

#!/usr/bin/env python
from socket import *
HOST='127.0.0.1'
PORT=27900
BUFFERSIZE=1024
ADDR=(HOST, PORT)
MAXCONNECTIONS=5

svrSocket=socket(AF_INET, SOCK_STREAM)
svrSocket.bind(ADDR)
svrSocket.listen(MAXCONNECTIONS)
while 1:
    print "Waiting for a client to connect..."
    cltSocket, client_info = svrSocket.accept()
    print "Client connected:", client_info

    while 1:
        recv_data = cltSocket.recv(BUFFERSIZE)
        if not recv_data: break
        print recv_data
        cltSocket.send(recv_data)
    cltSocket.close()

svrSocket.close()

Client:

#!/usr/bin/env python
from socket import *
HOST='127.0.0.1'
PORT=27900
BUFFERSIZE=1024
ADDR=(HOST,PORT)
MAXCONNECTIONS=5

sockToSvr=socket(AF_INET, SOCK_STREAM)
sockToSvr.connect(ADDR)

while 1:
    send_data = raw_input('>> ')
    if not send_data: break
    sockToSvr.send(send_data)
    talkBack = sockToSvr.recv(BUFFERSIZE)
    if not talkBack: break
    print talkBack

sockToSvr.close()

Now, this example isn't terribly useful, as it just takes raw input from the client, sends it to the server, which sends it back to the client. However, this very simple sort of client/server is quite useful for things like service and hardware monitoring, trend analysis, etc. Combine this sort of simple code with RRDTool and Apache, for example, and you get a massively configurable trend analysis system that is only limited by your imagination. Drop the data into MySQL for later retrieval, use the built in hashing modules to verify script versions, dump RPM versions into a database, use xml instead of databases, and so forth. In other words ... take this simple concept and have fun with it.

Tags:   python     |    Perm Link:   Python and network sockets



James Conner