Home > Backend Development > Python Tutorial > Python network programming uses select to implement socket full-duplex asynchronous communication function

Python network programming uses select to implement socket full-duplex asynchronous communication function

不言
Release: 2018-04-09 14:57:36
Original
4051 people have browsed it

This article mainly introduces the use of select in Python network programming to realize the socket full-duplex asynchronous communication function. It is shared with everyone here. Friends in need can refer to it.

The examples in this article describe the use of Python network programming. Select implements socket full-duplex asynchronous communication function. Share it with everyone for your reference, the details are as follows:

In the previous article "Simple Usage of TCP Sockets in Python Network Programming", we implemented the communication between the tcp client and the server, but the function is very limited. Sending and receiving messages cannot occur at the same time.

Next, I will select this module to achieve full-duplex communication (information can be received and sent at any time). Of course, it can also be completed with multi-threading, which is a story later.

So, what is select?

select - In a single-threaded network server program, manage multiple socket connections

The prototype of select is (rlist,wlist,xlist[,timeout ]), where rlist is the object waiting to be read, wlist is the object waiting to be written, xlist is the object waiting for exception, and the last one is an optional object, specifying the waiting time, the unit is s.

select()The return value of the method is a triplet of prepared objects. If no object is ready within the timeout period, the return value will be an empty list.

It uses polling to achieve asynchronous communication.

In the following program, it currently mainly supports 1-to-1 communication. When either party sends the string '88', it indicates the end of communication.

Let’s take a look at the specific implementation:

The first is the server.

#!/usr/bin/python
'test TCP server'
from socket import *
from time import ctime
import select
import sys
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
input = [tcpSerSock, sys.stdin]   #input是一个列表,初始有欢迎套接字以及标准输入
while True:
  print 'waiting for connection...'
  tcpCliSock, addr = tcpSerSock.accept()
  print '...connected from:',addr
  input.append(tcpCliSock)  #将服务套接字加入到input列表中
  while True:
    readyInput,readyOutput,readyException = select.select(input,[],[]) #从input中选择,轮流处理client的请求连接(tcpSerSock),client发送来的消息(tcpCliSock),及服务器端的发送消息(stdin)
    for indata in readyInput:
      if indata==tcpCliSock:  #处理client发送来的消息
        data = tcpCliSock.recv(BUFSIZ)
        print data
        if data=='88':
          input.remove(tcpCliSock)
          break
      else:       #处理服务器端的发送消息
        data = raw_input('>')
        if data=='88':
          tcpCliSock.send('%s' %(data))
          input.remove(tcpCliSock)
          break
        tcpCliSock.send('[%s] %s' %(ctime(), data))
    if data=='88':
      break
  tcpCliSock.close()
tcpSerSock.close()
Copy after login

The following is the client code, which is very similar, except that it does not need to process the request information compared to the server.

#!/usr/bin/python
'test tcp client'
from socket import *
from time import ctime
import select
import sys
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
input = [tcpCliSock,sys.stdin]
while True:
  readyInput,readyOutput,readyException = select.select(input,[],[])
  for indata in readyInput:
    if indata==tcpCliSock:
      data = tcpCliSock.recv(BUFSIZ)
      print data
      if data=='88':
        break
    else:
      data = raw_input('>')
      if data=='88':
        tcpCliSock.send('%s' %(data))
        break
      tcpCliSock.send('[%s] %s' %(ctime(), data))
  if data=='88':
    break
tcpCliSock.close()
Copy after login

So far, one-to-one full-duplex chat communication has been achieved.

Of course we need to think about how to achieve many-to-many communication?

We know that a server can serve multiple clients, that is, the server and the client itself have a one-to-many relationship. So, can we use the server as an intermediary to convey information, thereby achieving What about many-to-many communication?

For example, if A wants to communicate with B, A sends the information to the server, and then forwards it to B through the server. If you write according to this idea, it should be possible to complete many-to-many communication. If you are interested, you can try it.

Related recommendations:

Simple usage of TCP sockets in Python network programming

##

The above is the detailed content of Python network programming uses select to implement socket full-duplex asynchronous communication function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template