Using Python to implement a simple multi-thread TCP server tutorial, pythontcp

Source: Internet
Author: User

Using Python to implement a simple multi-thread TCP server tutorial, pythontcp

I recently read "python core programming". The book implements a simple one-to-one TCPserver, but in actual use, the one-to-one situation is obviously not good, so I studied how to start different threads (processes) on the server side to implement each link to a thread.

In fact, python has considered this requirement in the class design. We only need to inherit SocketServer. BaseRequestHandler from our own server.
The server code is as follows:

#!/usr/bin/env python import SocketServer from time import ctime HOST = '' PORT = 21567 ADDR = (HOST, PORT) class MyRequestHandler(SocketServer.BaseRequestHandler):   def handle(self):     print '...connected from:', self.client_address     while True:       self.request.sendall('[%s] %s' % (ctime(),self.request.recv(1024))) tcpServ = SocketServer.ThreadingTCPServer(ADDR, MyRequestHandler) print 'waiting for connection...' tcpServ.serve_forever()

The client code is as follows (basically the same as in the book, but the closed link in the loop is commented out ):

#!/usr/bin/env python from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) while True:   tcpCliSock = socket(AF_INET, SOCK_STREAM)   tcpCliSock.connect(ADDR)   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()

From the client code, we can see that a new request is created every time a request is entered.
Test. After the server and client are started, enter the test in the client:

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.