如何使send()调用异步? [英] How to make send() call asynchronous?

查看:71
本文介绍了如何使send()调用异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器以 nc -l 1234

下面是使用事件循环的 select()调用在 recv()上未被阻止的客户端.

Below is the client that is not blocked on recv() using event loop's select() call.

import socket
import sys
from eventloop import EventLoop

class Connection():
    def __init__(self):
        self.sock = socket.socket()
        self.sock.connect(('localhost', 1234))

    def fileno(self):
        return self.sock.fileno()

    def onRead(self):
        msg = self.sock.recv(1000).decode('utf-8')
        print(msg)

    def send(self, msg):
        self.sock.send(msg)

class Input():
    def __init__(self, sock):
        self.sock = sock

    def fileno(self):
        return sys.stdin.fileno()

    def onRead(self):
        msg = sys.stdin.readline().encode('utf-8')
        self.sock.send(msg)

sock = Connection()
inputReader = Input(sock)

eventLoop = EventLoop()
eventLoop.addReader(sock)
eventLoop.addReader(inputReader)
eventLoop.runForever()


eventloop.py

import select

class EventLoop():
    def __init__(self):
        self.readers = []

    def addReader(self, reader):
        self.readers.append(reader)

    def runForever(self):
        while True:
            readers, _, _ = select.select(self.readers, [], [])
            for reader in readers:
                reader.onRead()


但是 self.sock.send(msg)调用可能由于不同的原因而被阻止:


But self.sock.send(msg) call can get blocked for different reasons:

1)服务器崩溃

2)由于网络电缆断开,无法访问远程服务器(不是 localhost )

2) Remote server(not localhost) is not reachable, due to broken network cable

如何使 send()通话不被阻止?通过仅抛出消息并继续其余功能...而不使用 asyncio

How to make send() call not blocked? by just throwing the message and continue with rest of the functionality... without using asyncio

推荐答案

如何使send()调用不被阻止?

How to make send() call not blocked?

通过使用非阻塞套接字,即 self.sock.setblocking(0).请注意,尽管那时发送可能会失败,但您必须抓住这一点.发送也可能不会发送所有给定的数据,但是在阻塞套接字的情况下也是如此,而您只是忽略了这个问题.

By using a non-blocking socket, i.e. self.sock.setblocking(0). Be aware though that a send might fail then and you have to catch this. A send might also not send all given data, but this is also true with blocking sockets and you just ignored this problem.

鉴于您当前在阻塞 connect 上没有问题,您应该仅在阻塞 connect 之后将套接字设置为非阻塞.或者,您必须处理实现非阻塞连接的过程,这会比较棘手.

Given that you currently have no problems with your blocking connect you should set the socket to non-blocking only after the blocking connect. Or you have to deal with implementing a non-blocking connect which is a bit more tricky.

这篇关于如何使send()调用异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆