在Python中,是否可以在不编写字节操作管道代码的情况下将两个套接字连接在一起?
例如,我想编写一个与用户交互的程序(请求/响应格式),然后执行与另一台主机的 TCP 连接,然后将其交给 STDIN/STDOUT 套接字。
因此,在 STDIN 上接收到的任何数据都将通过 TCP 套接字发送,并且从 TCP 套接字接收到的任何数据都将同时、立即发送到 STDOUT,而不会阻塞。
推荐的方法是什么?如果可能的话,我想避免编写大量套接字代码并让它“正常工作”。
编辑:我的第一篇文章没有回答操作员想要的内容。大幅修改。
"""
open another terminal and run
nc -l 8080
type something in the both terminals>
"""
import sys
from socket import socket, AF_INET, SOCK_STREAM
from select import select
host = 'localhost'
port = 8080
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
reader = sock.makefile('r', 0)
writer = sock.makefile('w', 0)
while True:
ins, _, _ = select([reader, sys.stdin],[],[])
for i in ins:
if i == reader:
sys.stdout.write(i.read(1))
if i == sys.stdin:
writer.write(sys.stdin.read(1))
Run Code Online (Sandbox Code Playgroud)