与Python的非阻塞套接字通信

时间:2016-03-08 18:39:32

标签: python sockets

我正在编写一个通过套接字进行通信的小型Python代码,但我无法做到这一点,因此发送和接收是绝对独立的操作,即无需等待响应才能发送另一个信息。我目前的代码如下:

#!/usr/bin/python3
import argparse
import json
import socket
import time
import readline

parser = argparse.ArgumentParser(description='Client')
parser.add_argument("address", metavar= "Address", type=str,nargs=1, help="Server IP")
parser.add_argument("port",metavar="Port", type=str, nargs=1, help="Port to use")
args = parser.parse_args()
addr = args.address[0]
port = int(args.port[0])
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Connecting to {0} on port {1}".format(addr, port))
try:
    sock.connect((addr, port))
    print("Successfully connected to {0}".format(addr))
except Exception as e:
    raise(e)


sock.settimeout(60)
while True:
    msg = input("{0} | Out: ".format(time.strftime("%H:%M:%S")))
    words = msg.split(" ")
    if(words[0] == "connmobi"):
        words = "connect MOBIPIN-02000152 D4:F5:13:6B:77:A6".split(" ")
    data = json.dumps({"command":words[0],"args": [word for word in words[1:]]})
    sock.send("{0}\n".format(data).encode())
    try:
        data = sock.recv(1024).decode().strip('\n')
    except socket.timeout:
        continue

    print("{0} | In: {1}".format(time.strftime("%H:%M:%S"), data))
    if data == "bye":
        sock.close()
        print("Socket closed")
        break

如何“分离”接收和读取套接字的操作?

1 个答案:

答案 0 :(得分:0)

这绝不是一个简单的解决方案,但你可以看看python asyncio。 https://docs.python.org/3/library/asyncio-protocol.html

这些模块专门用于套接字的异步处理。快速搜索后,我找到了一个可能对您有所帮助的示例。 https://gist.github.com/dbehnke/c8f64cb6e67afff437c1