Python equivalent of `io.Copy`

huangapple go评论80阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2017年1月8日 14:53:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/41530272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定