Friday, June 08, 2007


Python Server Start

Here's another one of those code snippets that I think I might want to find again someday. Nobody else will care.

This is a Python script that opens a port and accepts connections from clients. This is just a starting point for all the little mock servers I write with Python for testing and diagnostics. I'm tired of copying and pasting the little bits of various Python tutorials that I usually do whenever I have to make a new one of these, so here is my new standard starting point.

I can hack this up by changing the data_received() method to deal with requests coming from the client, and can also hack up run() to get the server to send data to the client unsolicited.

[UPDATE: See more advanced version: Python Server Start, Take 2]

Simple server

This is a simple Python script that simulates a server.
It is intended for use with the unit tests; this is not production code.

Currently, it has these features:

- Starts listening for connections on port 64123

- Prints all data received from clients


import sys
import os
import socket
import threading

defaultAddr = 'localhost'
defaultPort = 64123

class ClientThread(threading.Thread):
  Thread for handling communication with a single client.
  def __init__(self, client, address):
    self.client = client
    self.address = address

  def run(self):
    running = 1
    while running:
      data = self.client.recv(1024)
      if data:
        print "Connection", self.address, "closed"
        running = 0

  def data_received(self, data):
    Called by run() when data is received
    print "Data received %s: [%s]" % (self.address, data)

def RunServer():
  Open server socket and accept connections
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  print "Bind to %s:%d" % (defaultAddr, defaultPort)
  s.bind((defaultAddr, defaultPort))
  print "Listening for connections..."
  while 1:
    (client, address) = s.accept()
    print 'Accepted connection from', address
    ct = ClientThread(client, address)

if __name__ == "__main__":

Couldn't you just use netcat for that?
Netcat would do what this script does as-is, but the reason for having this starting point is to start hacking it up to do complicated things when it receives data, or to send data to the client.
Wouldn't the standard library SocketServer (in either its forking or threaded variants) do what you want here? Mind you, as someone is fond of telling me, it's pretty easy to reinvent the wheel with Python ...

Yeah, maybe SocketServer is what I want. Thanks for the pointer; I'll need to investigate...
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?