在python中创建非阻塞套接字 [英] Creating non-blocking socket in python

查看:61
本文介绍了在python中创建非阻塞套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解非阻塞套接字是如何工作的,所以我用 python 编写了这个简单的服务器.

I was trying to understand how non-blocking sockets work ,so I wrote this simple server in python .

import socket

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(('127.0.0.1',1000))
s.listen(5)
s.setblocking(0)
while True:
      try:
            conn, addr = s.accept()
            print ('connection from',addr)
            data=conn.recv(100)
            print ('recived: ',data,len(data))

      except:
          pass  

然后我尝试从这个客户端的多个实例连接到这个服务器

Then I tried to connect to this server from multiple instances of this client

import socket

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',1000))
while True:
    continue

但由于某种原因,将阻塞设置为 0 或 1 似乎没有效果,并且服务器的 recv 方法总是阻塞执行.因此,在 python 中创建非阻塞套接字需要的不仅仅是将阻塞标志设置为 0.

But for some reason putting blocking to 0 or 1 dose not seem to have an effect and server's recv method always block the execution. So, dose creating non-blocking socket in python require more than just setting the blocking flag to 0.

推荐答案

setblocking 仅影响您使用它的套接字.因此,您必须添加 conn.setblocking(0) 才能看到效果:如果没有可用数据,recv 将立即返回.

setblocking only affects the socket you use it on. So you have to add conn.setblocking(0) to see an effect: The recv will then return immediately if there is no data available.

这篇关于在python中创建非阻塞套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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