【问题标题】:Easiest Way to Transfer Data Over the Internet, Python通过 Internet 传输数据的最简单方法,Python
【发布时间】:2011-08-23 17:05:09
【问题描述】:

我有两台电脑,都连接到互联网。我想在它们之间传输一些基本数据(字符串、整数、浮点数)。我是网络新手,所以我正在寻找最简单的方法来做到这一点。我会看哪些模块来做到这一点?

两个系统都将运行 Windows 7。

【问题讨论】:

  • 刚刚做到了!我给了很多人他们应得的荣誉。
  • 而且,帮助自己在未来获得更多答案 :) 你是少数真正倾听的人之一

标签: python networking data-transfer


【解决方案1】:

只要不是异步的(同时发送和接收),你可以使用the socket interface

如果你喜欢抽象(或需要异步支持),总有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 流......)

【讨论】:

    【解决方案2】:

    如果你完全不知道什么是套接字,那么使用 Twisted 可能会有点困难。而且由于您需要识别正在传输的数据的类型,事情会变得更加困难。

    所以也许ICE, the Internet Communication Engine的python版本会更适合,因为它隐藏了很多网络编程的肮脏细节。看看hello world,看看它是否能帮到你。

    【讨论】:

      【解决方案3】:

      看这里: 如果您像我认为的那样尝试使用套接字,这就是您要寻找的: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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-28
        • 2015-11-25
        • 2010-12-27
        • 1970-01-01
        相关资源
        最近更新 更多