![](/img/trans.png)
[英]What is the most lightweight way to transmit data over the internet using Python?
[英]Easiest Way to Transfer Data Over the Internet, Python
我有兩台電腦,都連接到互聯網。 我想在它們之間傳輸一些基本數據(字符串,整數,浮點數)。 我是網絡新手,所以我正在尋找最簡單的方法。 我會在做什么模塊來做這件事?
兩個系統都將運行Windows 7。
只要它不是異步(一次發送和接收),就可以使用套接字接口 。
如果您喜歡抽象(或需要異步支持),那么總會有Twisted。
這是套接字接口的一個例子(當你的程序變大時會越來越難用,所以我建議使用Twisted或asyncore )
import socket
def mysend(sock, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("where ever you have your other computer", "port number"))
i = 2
mysend(s, str(i))
python文檔非常好,我從那里獲取了mysend()函數。
如果您正在進行與計算相關的工作,請查看XML-RPC ,哪些python已經為您精心打包。
請記住,套接字就像文件一樣,所以編寫代碼並沒有太大的不同,所以,只要你能做基本文件io,並了解事件,套接字編程就不難了(只要你不會像復用VoIP流那樣復雜......)
如果你完全不知道什么是套接字,那么使用Twisted可能有點困難。 而且,由於您需要確定所傳輸數據的類型,因此事情會變得更加困難。
所以也許是ICE的python版本,Internet通信引擎將更適合,因為它隱藏了很多網絡編程的臟細節。 看看你好世界 ,看看它是否能起作用。
看看這里:如果您,我認為您正在嘗試使用套接字,那么您正在尋找: https : //docs.python.org/2/howto/sockets.html
我希望這會有所幫助,因為它對我有用。 或添加此類以進行持續連接:
class mysocket:
'''demonstration class only
- coded for clarity, not efficiency
'''
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(self, host, port):
self.sock.connect((host, port))
def mysend(self, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def myreceive(self):
chunks = []
bytes_recd = 0
while bytes_recd < MSGLEN:
chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
if chunk == '':
raise RuntimeError("socket connection broken")
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
return ''.join(chunks)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.