A tutorial on using Python to implement a simple multithreaded TCP server

Source: Internet
Author: User
Tags socket

This article mainly introduces the use of Python to implement a simple multithreaded TCP server tutorial, the example of the operating environment for the Windows operating system, the need for friends can refer to the

Recently read "Python core programming", the book implemented a simple 1 to 1 of the tcpserver, but in the actual use of 1 to 1 of the situation is obviously not, so the study of how to start a different thread (process) on the server side to implement each link one thread.

In fact, Python in the design of the class has taken into account the needs of this aspect, we only have to inherit the Socketserver.baserequesthandler on their own server.

The server-side code is as follows:

?

1 2 3 4 5 6 7 8 9 10 11 12 13-14 #!/usr/bin/env python import socketserver from time import ctime HOST = ' PORT = 21567 ADDR = (HOST, PORT) class Myreques Thandler (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 (basic and identical in the book, except that the closing link in the loop is commented out):

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17-18 #!/usr/bin/env python from socket import * host = ' localhost ' PORT = 21567 Bufsiz = 1024 ADDR = (HOST, PORT) while True:t Cpclisock = socket (af_inet, Sock_stream) tcpclisock.connect (ADDR) data = Raw_input (' > ') if not data:break tcpclisock. Send ('%SRN '% data) data = TCPCLISOCK.RECV (bufsiz) if not data:break print Data.strip () #tcpCliSock. Close ()

You can see from the client's code that each input creates a new request.

Test, after starting server and client, enter the test in client:

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.