A brief analysis of python network programming examples


This article is an example of python network programming, to share with you for your reference.

Specific methods are as follows:

The server code is as follows:

from SocketServer import(TCPServer as TCP,
             StreamRequestHandler as SRH)
from time import ctime

HOST = ''
PORT = 21567
ADDR = (HOST, PORT)
class MyRequestHandle(SRH):
  def handle(self):
    print 'connecting from ..', self.client_address
    self.wfile.write("[%s]:%s" %
             (ctime(),self.rfile.readline())
             )
tcp_Server = TCP(ADDR,MyRequestHandle)
print 'WAITING connecting...'
tcp_Server.serve_forever()

The client code is as follows:

from socket import *

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

while True:
  tcpCliSock = socket(AF_INET,SOCK_STREAM)
  tcpCliSock.connect(ADDR)
  data = raw_input('>>>')
  if not data:
    break
  tcpCliSock.send("%srn" % data)
  data = tcpCliSock.recv(BUFSIZE)
  if not data:
    break
  print data.strip()
  tcpCliSock.close()

I hope this article has helped you with your Python programming.