Nov 13, 2011

Socket Programming with Python - Echo server

This is a basic socket program. You need to run the server first and then run the client.

Echo server (pechoserver.py)
#!/usr/bin/python

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("",5200)) # server is running on Port 5200
s.listen(1)

while 1:
 conn, addr = s.accept()
 print 'Connected IP ' , addr
 data = conn.recv(1024)
 if not data:
  break
 conn.send(data)
 conn.close()


Echo client (pechoclient.py)
#!/usr/bin/python

import socket
import sys

if (len(sys.argv)<1):
        print 'usage : pechoclient.py "message"'
        exit(0)
else:
        msg=sys.argv[1]
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect(("localhost",5200))
        s.send(msg)
        data=s.recv(1024)
        s.close()
        print "Recived : " ,data


Run the server ;
$ pyhton pechoserver.py &

Run the client ;
$ python pechoclient "Hello World."

Run client and server in different terminals to get a clear understanding of the output.

For more : http://docs.python.org/library/socket.html
                 http://docs.python.org/howto/sockets.html

No comments:

Post a Comment

Your comments are always welcome ...