Saturday, September 19, 2009

Python - a simple echo server using socket

# a simple echo server
# it will run indefinitely -- Control-C to kill!

#
# test your server with the simple client script


import socket


host = ''
port = 54321
connections = 5
size = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(connections)

print "echo server started..."
while 1:
    client, address = s.accept()
    data = client.recv(size)
    if data:
        print "connection from: %s" %(str(address[0]))
        client.send(data)
    client.close()


#output:
## when the server starts:
# echo server started...
## when a client sends data:
# connection from: 127.0.0.1

No comments:

Post a Comment