Python Network Programming

Source: Internet
Author: User

Today learned a Python network programming, feel relatively simple, that is, the basic steps, Create--bind---listen-->receive/send---->close.

Also learn a TCP version of the server programming framework that can support multiple socket connections. The feeling is also possible. The simplest of these frameworks is Tcpserver+baserequesthandler:. A simple example is as follows:

Import socketserver# This program can support multiple client connection requests class Myrequesthandler (Socketserver.baserequesthandler): # Self.request is actually a socketdef handle (self): addr =self.request.getpeername () print "Got connection from", Addrwhile True: #当客户端主动断开连接时, SELF.RECV (1024) throws an exception try: #read a byte of each time, and remove the empty letter including (Space tab \ r \ n) data = s ELF.REQUEST.RECV (1024x768). Strip () if not Data:breakprint "receive from (%s):%s"% (Self.client_address,data) Self.request.sendall (Data.upper ()) Except:traceback.print_exc () Breakself.request.close () addr= (' 127.0.0.1 ', 8000) Server =socketserver.threadingtcpserver (Addr,myrequesthandler) server.serve_forever ()  #只是反复调用handle_request ( ) #server. Handle_request () #一个一个的处理链接请求.


The client is:

# *_* coding=gb2312 *-*import timeimport sysimport loggingfrom socket Import *host = "127.0.0.1" port = 8000def Test (): Glob Al Host,portbufsize=1024#print "Hello World" #logging. Warn ("There is some error") Client =socket (Af_inet,sock_stream) Client.connect ((Host,port)) while True:data =raw_input (' Please input sending data: ') if not data or data = = "Exit": Breakclient.send ("%s"% data) data =client.recv (bufsize) if not data:breakprint Data.strip () client.close () if __name__ = = ' __main__ ': Test ()


Python Network Programming

Related Article

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.