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]
#!/usr/bin/python
"""
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):
threading.Thread.__init__(self)
self.client = client
self.address = address
def run(self):
running = 1
while running:
data = self.client.recv(1024)
if data:
self.data_received(data)
else:
print "Connection", self.address, "closed"
self.client.close()
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))
s.listen(5)
print "Listening for connections..."
while 1:
(client, address) = s.accept()
print 'Accepted connection from', address
ct = ClientThread(client, address)
ct.start()
#
# MAIN
#
if __name__ == "__main__":
RunServer()
Cheers,
--dt
<< Home




