英文:
Python equivalent of `io.Copy`
问题
我正在尝试使用Python实现一个TCP代理,所以我需要直接连接两个套接字,并在它们之间传递输入和输出。
在Golang中,我可以简单地使用io.Copy
来实现,那么在Python 2.6中有没有相当的方法呢?
import threading
def copy_data(source, destination):
while True:
data = source.recv(4096)
if not data:
break
destination.sendall(data)
# 在你的代码中调用这个函数
thread1 = threading.Thread(target=copy_data, args=(conn1, conn2))
thread2 = threading.Thread(target=copy_data, args=(conn2, conn1))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
这段代码创建了两个线程,分别用于从conn1
复制数据到conn2
,以及从conn2
复制数据到conn1
。这样就实现了在两个套接字之间传递数据的功能。
英文:
I'm trying to implement a tcp proxy with python,
So I need to connect two sockets directly, passing input and output in between.
In golang, I simply do a io.Copy
, what's the equivalent in Python 2.6?
go func() {
defer conn1.Close()
defer conn2.Close()
io.Copy(conn1, conn2)
}()
答案1
得分: 2
你可以使用以下类似的函数:
def CopyProxy(conn1, conn2):
while True:
data = conn2.recv(BUFFER_SIZE)
try:
conn1.send(data)
if not data:
conn1.close()
conn2.close()
break
except Exception:
break
然后在单独的线程中启动它们:
# conn1 和 conn2 是之前打开的连接 "to" 和 "from"
t1 = threading.Thread(target=CopyProxy, args=[conn1, conn2])
t2 = threading.Thread(target=CopyProxy, args=[conn2, conn1])
t1.start()
t2.start()
英文:
You may use function like this:
def CopyProxy(conn1, conn2):
while True:
data = conn2.recv(BUFFER_SIZE)
try:
conn1.send(data)
if not data:
conn1.close()
conn2.close()
break
except Exception:
break
Then launch them in separate threads:
# conn1 and conn2 - previously opened connections "to" and "from"
t1 = threading.Thread(target=CopyProxy, args=[conn1, conn2])
t2 = threading.Thread(target=CopyProxy, args=[conn2, conn1])
t1.start()
t2.start()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论