2010年6月23日 星期三

Sockets in Python: Into the World of Python Network Programming - A Simple Echo Server

Step1:
Client send message to Server.
When Server receive the message, Server will send 'echo' back.

Step2:
Client send nothing to Server.
When Server receive nothing, Server will terminate the process.


Server

#! /usr/bin/env python
from socket import *

HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)

print 'waiting for connection'
(clientsock, addr) = serversock.accept()
print 'connected from:', addr

while 1:
data = clientsock.recv(BUFSIZ)
print data
if not data: break
clientsock.send('echoes')

clientsock.close()
serversock.close()

Client :

#! /usr/bin/env python
from socket import *

HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpClientSock = socket(AF_INET, SOCK_STREAM)
tcpClientSock.connect(ADDR)

while 1:
data = raw_input('> ')
if not data: break
tcpClientSock.send(data)

data = tcpClientSock.recv(1024)
if not data: break
print data

tcpClientSock.close()

Related Posts:

0 意見:

張貼留言