Python Network Programming

Source: Internet
Author: User

Python Network Programming

Today I learned a python network programming, which is relatively simple, that is, the basic steps. create -- bind --- listen --> receive/send ----> close.

I also learned a Tcp Server programming framework that supports multiple socket connections. It also works. The simplest framework is TCPServer + BaseRequestHandler :. A simple example is as follows:

Import SocketServer # This program can support multiple client connection requests class MyRequestHandler (SocketServer. baseRequestHandler): # self. the request is actually a socketdef handle (self): addr = self. request. getpeername () print got connection from, addrwhile True: # When the client actively disconnects, self. recv (1024) throws an exception. try: # read 1024 byte each time, and remove empty letter including (space tab) data = self. request. recv (1, 1024 ). strip () if not data: breakprint receive from (% s): % s % (se Lf. client_address, data) self. request. sendall (data. upper () failed T: traceback. print_exc () breakself. request. close () addr = ('2017. 0.0.1 ', 8000) server = SocketServer. threadingTCPServer (addr, MyRequestHandler) server. serve_forever () # Just call handle_request () # server. handle_request () # process link requests one by one.


The client is:

# *_* coding=gb2312 *-*import timeimport sysimport loggingfrom socket import *host = 127.0.0.1port = 8000def Test():global host,portbufsize=1024#print Hello world#logging.warn(there are some error)client =socket(AF_INET,SOCK_STREAM)client.connect((host,port))while True:www.bkjia.comdata =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()

 

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.