rectangletangle rectangletangle - 1 year ago 94
Python Question

Easiest Way to Transfer Data Over the Internet, Python

I have two computers, both are connected to the internet. I'd like transfer some basic data between them (strings, ints, floats). I'm new to networking so I'm looking for the most simple way to do this. What modules would I be looking at to do this?

Both systems would be running Windows 7.

Answer Source

As long as its not asynchronous (doing sending and receiving at once), you can use the socket interface.

If you like abstractions (or need asynchronous support), there is always Twisted.

Here is an example with the socket interface (which will become harder to use as your program grows larger, so, I would suggest either Twisted or 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))

The python documentation is excellent, I picked up the mysend() function from there.

If you are doing computation related work, check out XML-RPC, which python has all nicely packaged up for you.

Remember, sockets are just like files, so they're not really much different to write code for, so, as long as you can do basic file io, and understand events, socket programming isn't hard, at all (as long as you don't get too complicated like multiplexing VoIP streams...)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download