Sockets in Python: Into the World of Python Network Programming - A Simple Echo Server (
Page 3 of 4 )
Now that the steps are clear, let's create a simple echo server. First the imports:
from socket import *
Then the constants that defines the host, port, buffer size and the address tuple to be used with bind().
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
Then we create the server side socket and bind it to the host and the port. Then comes the max queue size to 2:
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)
Now, to make it listen for incoming requests continuously, place the accept() method in a while loop. This is not the most preferred mode. The preferred way will be discussed in the next section:
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)
while 1:
print 'waiting for connection…'
clientsock, addr = serversock.accept()
print '…connected from:', addr
:
:
Next, receive the data from the client and echo it back. This has to continue until the client doesn’t send the null data or ctrl+c. To achieve this, use a while loop again and then close the connection when done.
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)
while 1:
print 'waiting for connection…'
clientsock, addr = serversock.accept()
print '…connected from:', addr
while 1:
data = clientsock.recv(BUFSIZ)
if not data: break
clientsock.send(‘echoed’, data)
clientsock.close()
serversock.close()
That’s all for the server. Now for the client. The only exception is that there is no bind(), accept() and listen().
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while 1:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
data = tcpCliSock.recv(1024)
if not data: break
print data
tcpCliSock.close()