python阻止套接字,立即发送返回值 [英] python blocking sockets, send returns immediately

查看:110
本文介绍了python阻止套接字,立即发送返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用套接字模块在Python中编写多线程套接字应用程序. 服务器侦听连接,当连接建立后,它会为该套接字生成一个线程.

I am writing a multithreaded socket application in Python using the socket module. the server listens for connections and when it gets one it spawns a thread for that socket.

服务器线程将一些数据发送到客户端.但客户尚未准备好接收它.我以为这会导致服务器等到客户端启动recv,而是立即返回

the server thread sends some data to the client. but the client is not yet ready to receive it. I thought this would have caused the server to wait until the client starts recv but instead returns immediately

然后,客户端调用已阻止的recv,并且从未接收到任何数据.

the client then calls recv which is blocking and no data is ever received.

客户端套接字构造器

self.__clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__clientSocket.connect((server, port))

服务器套接字构造器

        self.servSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.servSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        #self.servSock.settimeout(None)
        self.servSock.setblocking(1)
        self.servSock.bind((self.addr,self.port))
        self.servSock.listen(5)

监听接受线程

    try:
        (cs, address) = self.servSock.accept()
    except socket.timeout:
        return
    threadName = '\r\nClient %s:%s\r\n' % (cs, address)
    print threadName
    clientSocketHandler = ClientSocket()
    clientSocketHandler.setClientSocket(cs)
    self.clients.newThread(self.clientFunc, {clientSocketHandler : "1"}, threadName).start()

服务器和客户端从ClientSocket内部发送/接收方法

server and clients send/rec methods from inside ClientSocket

receivedData = self.__clientSocket.recv(1024*1024)

self.__clientSocket.send(s)

任何想法为何send()立即返回?

any ideas why send() is returning straight away?

推荐答案

任何想法为何send()立即返回?

any ideas why send() is returning straight away?

所有send()所做的工作都是填充网络缓冲区并返回发送的字节数.

all send() does is fill the network buffer and return the ammount of bytes sent.

如果您想要阻止发送,只需从客户端接收确认消息即可.

if you want a send that blocks just recv an acknowledgement message from the client.

这篇关于python阻止套接字,立即发送返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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