仅在发送python套接字时接收数据

时间:2017-03-31 20:14:06

标签: python-3.x sockets try-catch recv

我在python中编写一个messenger应用程序,我遇到了问题。问题很简单:我希望程序只接收来自其他计算机的数据,否则,我的程序会无限期地等待数据传输。我该如何编写这段代码?我想它会是这样的:

    try:
        data = s.recv(1024).decode()
    except:
        data == None

1 个答案:

答案 0 :(得分:2)

请参阅select模块。可以通过超时监视套接字的可读性,以便继续进行其他过程。

示例服务器:

import socket
import select

with socket.socket() as server:
    server.bind(('',5000))
    server.listen(3)
    to_read = [server]  # add server to list of readable sockets.
    clients = {}
    while True:
        # check for a connection to the server or data ready from clients.
        # readers will be empty on timeout.
        readers,_,_ = select.select(to_read,[],[],0.5)
        for reader in readers:
            if reader is server:
                client,address = reader.accept()
                print('connected',address)
                clients[client] = address # store address of client in dict
                to_read.append(client) # add client to list of readable sockets
            else:
                # Simplified, really need a message protocol here.
                # For example, could receive a partial UTF-8 encoded sequence.
                data = reader.recv(1024)
                if not data: # No data indicates disconnect
                    print('disconnected',clients[reader])
                    to_read.remove(reader) # remove from monitoring
                    del clients[reader] # remove from dict as well
                else:
                    print(clients[reader],data.decode())
        print('.',flush=True,end='')

一个简单的客户端,假设您的IP地址是1.2.3.4。

import socket
s = socket.socket()
s.connect(('1.2.3.4',5000))
s.sendall('hello'.encode())
s.close()