Python multi-threaded socket programming method for multiple client access

Source: Internet
Author: User
This article mainly for you in detail the Python multi-threaded socket programming multiple client access, with a certain reference value, interested in small partners can refer to

The server that implements socket communication in Python is complex, and the client is very simple, so the client is basically implemented by the SOCKCT module, and the service
There are many modules that can be used for the end, as follows:

1, the Client


#!/usr/bin/env python#coding:utf-8 ' File:client.pydate:9/9/17 3:43 pmauthor:lockeyemail:lockey@123.comdesc: Socket programming client, python3.6.2 ' Import socket,syshost = ' 192.168.1.6 ' PORT = 8998ADDR = (host,port) BUFSIZE = 1024sock = Socket.socket () try:sock.connect (ADDR) print (' has connected with server ') while True:  data = input (' lockey# ')  If Len (data) >0:  print (' Send: ', data)  Sock.sendall (Data.encode (' Utf-8 ')) #不要用send ()  recv_data = SOCK.RECV (BUFSIZE)  print (' Receive: ', Recv_data.decode (' Utf-8 '))  else:  sock.close ()  breakexcept Exception:print (' ERROR ') Sock.close () Sys.exit ()


2. Socketserver Module

In order to enable multiple clients to access the service and communicate at the same time, the server will use the Socketserver module to implement, so that the user does not have to use the parent process to process it after the child thread ends, and does not care about the socket closure, everything is done by Socketserver.


#!/usr/bin/env python#coding:utf-8 "' File:client.pydate:9/9/17 3:43 PMauthor:lockeyemail: Lockey@123.comdesc:socket programming server side, python3.6.2 ' from socketserver import Baserequesthandler, Threadingtcpserverimport threadingbuf_size=1024class Handler (baserequesthandler): def handle (self): Address,pid = Self.client_address print ('%s connected! '     %address) While true:data = Self.request.recv (buf_size) If Len (data) >0:print (' receive= ', Data.decode (' Utf-8 ')) Cur_thread = Threading.current_thread () #response = ' {}:{} '. Format (cur_thread.ident,data) Self.request.sendall (' Response '. Encode (' Utf-8 ')) print (' Send: ', ' response ') else:print (' Close ') breakif __name__ = = ' __main__ ': HOST = ' 192.168.1.6 ' PORT = 8998 ADDR = (host,port) server = Threadingtcpserver (addr,handler) #参数为监听地址和已建立连接的处理类 print (' Listeni Ng ') server.serve_forever () #监听, after a TCP connection is established, a new socket and thread is created for the connection, and the handle method in the processing class handles the print (server) 

In the following tests, I use the other host and the two interrupts of the machine to connect to the server, can be connected properly and can be interactive data reply

Note: This program example runs on platform Rhel7.2.x86_64,python version 3.6.2, for the Windows platform and non-identical Python version of the user may lack some compatibility, if other platform users please fix it yourself!!

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.