通过互联网传输数据最简单的方法,Python
问题描述:
我有两台电脑,都连接到互联网。我想在它们之间传输一些基本数据(字符串,整数,浮点数)。我是新来的网络,所以我正在寻找最简单的方法来做到这一点。我会在看什么模块来做到这一点?通过互联网传输数据最简单的方法,Python
两个系统都将运行Windows 7
答
只要它不是异步(做发送和一次接收),你可以使用the socket interface。
如果你喜欢抽象(或需要异步支持),总有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流那么复杂...)
答
如果你完全不知道什么是socket,那么使用Twisted可能有点困难。而且,由于您需要确定正在传输的数据的类型,事情会变得更加困难。
所以也许python版本的ICE, the Internet Communication Engine会更适合,因为它隐藏了很多网络编程的肮脏细节。看看hello world看看它是否做你的工作。
答
看看这里: 如果你,我想你,想使用套接字这是你在找什么: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)
刚刚做到了!我给了很多人他们应得的荣誉。 – rectangletangle 2011-05-12 04:57:47
而且,帮助你自己在未来获得更多答案:) 你是少数真正听过的人之一 – 2011-05-13 20:45:18