Python network programming details and simple examples, python network programming details

Source: Internet
Author: User

Python network programming details and simple examples, python network programming details

Python network programming details

The patent right for network programming should belong to Unix, various platforms (such as windows and Linux), various languages (such as C, C ++, Python, and Java) all syntaxes that conform to their own characteristics are similar. In my opinion, I understand the network programming of Unix socket, and other network programming methods. This sentence is not rigorous yet. It should be accurate to understand the principle of socket programming and network programming. The difference is that every platform and every language has its own exclusive syntax. We can simply apply it flexibly.

The following is an example of the most basic network programming implemented using python. It relies on the client-server architecture to achieve one-way "data flow" between the client and the server ". We use two methods respectively. One method is the most primitive socket programming, and the other method is to encapsulate and implement the first method using python's object-oriented method to reduce transparency, easy to develop.

Requirement: the client inputs data and sends it to the server. The server generates (timestamp + Data) encapsulated data to respond to the client. Socket programming includes two types: connection-oriented and connectionless. These two types correspond to TCP data streams and UDP data packets respectively. Therefore, we implement both methods.

I. Python socket programming

Connection-oriented TCP socket programming:

# -*- coding: utf-8 -*- 3 from socket import *from time import ctime # Address and PortHOST = ''PORT = 21567ADDR = (HOST, PORT)# BuffSizeBUFSIZ = 1024# build sockettcpSerSock = socket(AF_INET, SOCK_STREAM)# bind sockettcpSerSock.bind(ADDR)# listen 5 client tcpSerSock.listen(5)try:  while True:    print 'waiting for connection...'    # build client socket    tcpCliSock, addr = tcpSerSock.accept()    print '...connect from:', addr    # accept data and process    while True:      data = tcpCliSock.recv(BUFSIZ)      if not data:        break      tcpCliSock.send('[%s] %s' % (ctime(), data))      # close client socket       tcpCliSock.close()except EOFError, KeyboardInterrupt:  tcpSerSock.close()
# -*- coding:utf-8 -*-from socket import *# Address and Port HOST = '127.0.0.1'PORT = 21567ADDR = (HOST, PORT)# BufferSizeBUFSIZ = 1024#build socket tcpCliSocket = socket(AF_INET, SOCK_STREAM)tcpCliSocket.connect(ADDR)while True:  data = raw_input('> ')  if not data:    break  # send data  tcpCliSocket.send(data)  # recv data  data = tcpCliSocket.recv(BUFSIZ)  if not data:    break  # show data  print datatcpCliSocket.close()

Connectionless UDP socket programming

# -*- coding: utf-8 -*-from socket import *from time import ctime # Address and Port HOST = ''PORT = 8000ADDR = (HOST, PORT)# BufferSizeBUFFSIZE = 1024# build socketudpSerSock = socket(AF_INET, SOCK_DGRAM)# bind socketudpSerSock.bind(ADDR)try:  while True:    print 'waiting the message...'    data, addr = udpSerSock.recvfrom(BUFFSIZE)    print 'received the message: '+data+' from: ', addr    udpSerSock.sendto('[%s] %s' % (ctime(), data), addr)except EOFError, KeyboardInterrupt:  udpSerSock.close()
# -*- coding: utf-8 -*-from socket import *# Address and Port HOST = 'localhost'PORT = 8000ADDR = (HOST, PORT)# BufferSizeBUFSIZ = 1024# build socket udpCliSock = socket(AF_INET, SOCK_DGRAM)while True:  data = raw_input('> ')  udpCliSock.sendto(data, ADDR)  data = udpCliSock.recvfrom(BUFSIZ)  if not data:    break  print data udpCliSock.close()

2. Network Programming Based on encapsulation SocketServer

# -*- coding: utf-8 -*-from SocketServer import TCPServer as TCP, StreamRequestHandler as SRH from time import ctime # Address and PortHOST = ''PORT = 21567ADDR = (HOST, PORT)# BuffSizeBUFSIZ = 1024# build RequestHandlerclass MyRequestHandler(SRH):  def handle(self):    print '...connected from: ', self.client_address    self.wfile.write('[%s] %s' % (ctime(), self.rfile.readline()))# build TCPServerTCPServ = TCP(ADDR, MyRequestHandler)print 'waiting for connection...'# loop to processTCPServ.serve_forever()
#-*-Coding: UTF-8-*-from socket import * # Address and Port HOST = '2017. 0.0.1 'port = 21567 ADDR = (HOST, PORT) # BufferSizeBUFSIZ = 1024 while True: # note: The default act of the request processor of SocketServer is to accept connections. # Get the request, then close the connection, so you need to connect tcpCliSock = socket (AF_INET, SOCK_STREAM) tcpCliSock multiple times. connect (ADDR) # process data = raw_input ('>') if not data: break tcpCliSock. send ('% s \ r \ n' % data) data = tcpCliSock. recv (BUFSIZ) if not data: break print data. strip () tcpCliSock. close ()

Thank you for reading this article and hope to help you. Thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.