Home  >  Article  >  Backend Development  >  Methods to connect multiple clients in python multi-threaded socket programming

Methods to connect multiple clients in python multi-threaded socket programming

巴扎黑
巴扎黑Original
2017-09-13 09:39:161876browse

This article mainly introduces multi-client access in python multi-threaded socket programming in detail, which has certain reference value. Interested friends can refer to

Implementing socket communication in Python The server side is relatively complex, but the client side is very simple, so the client side is basically implemented using the sockct module, while the service side has many modules that can be used, as follows:

Methods to connect multiple clients in python multi-threaded socket programming

1. Client


#!/usr/bin/env python
#coding:utf-8
'''
file:client.py
date:9/9/17 3:43 PM
author:lockey
email:lockey@123.com
desc:socket编程客户端,python3.6.2
'''
import socket,sys
HOST = '192.168.1.6'
PORT = 8998
ADDR =(HOST,PORT)
BUFSIZE = 1024

sock = socket.socket()
try:
 sock.connect(ADDR)
 print('have 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()
  break
except Exception:
 print('error')
 sock.close()
 sys.exit()


2. SocketServer module

In order to allow multiple clients to access the service and communicate at the same time, the server will use the SocketServer module to implement it. In this way, the user does not need to use the parent process to process it after the child thread ends, and does not need to care about closing the socket. , everything is done by SocketServer.


#!/usr/bin/env python
#coding:utf-8
'''
file:client.py
date:9/9/17 3:43 PM
author:lockey
email:lockey@123.com
desc:socket编程服务器端,python3.6.2
'''
from socketserver import BaseRequestHandler,ThreadingTCPServer
import threading

BUF_SIZE=1024

class 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')
    break

if __name__ == '__main__':
 HOST = '192.168.1.6'
 PORT = 8998
 ADDR = (HOST,PORT)
 server = ThreadingTCPServer(ADDR,Handler) #参数为监听地址和已建立连接的处理类
 print('listening')
 server.serve_forever() #监听,建立好TCP连接后,为该连接创建新的socket和线程,并由处理类中的handle方法处理
 print(server)

In the following test, I used two interrupts from another host and this machine to connect to the server. Both of them can connect normally and can perform data response interaction

Methods to connect multiple clients in python multi-threaded socket programming

Note: The running platform of this program example is rhel7.2.x86_64, and the python version is 3.6.2. There may be a lack of compatibility for users on the windows platform and different python versions. If Users of other platforms please correct it yourself! !

The above is the detailed content of Methods to connect multiple clients in python multi-threaded socket programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn