bbc
bbc

Reputation: 240

Send strings over the network

Here's a simple question and I'm surprised I haven't come across a similar one already.

I would like two processes to send strings (messages) to each other with send() and receive() functions. Here's a basic example:

# Process 1
# ... deal with sockets, connect to process 2 ...
msg = 'An arbitrarily long string\nMaybe with line breaks'
conn.send(msg)
msg = conn.receive()
if process1(msg):
    conn.send('ok')
else:
    conn.send('nok')

and

# Process 2
# ... deal with sockets, connect to process 1 ...
msg = conn.receive()
conn.send(process2(msg))
msg = conn.receive()
if msg == 'ok':
    print('Success')
elif msg == 'nok':
    print('Failure')
else:
    print('Protocol error')

I know it is quite easy with bare stream sockets, but that's still cumbersome and error prone (do several conn.recv() inside a loop and check for size, like HTTP or end of stream marker, like SMTP, etc).

By the way, it doesn't necessarily need to use sockets, as long as messages of any size can be reliably carried through the network in an efficient manner.

Am I doing something wrong? Isn't there a simple library (Twisted AMP doesn't look simple) doing exactly that? I've been searching the Internet for a few hours without success :)

Upvotes: 1

Views: 647

Answers (1)

mguijarr
mguijarr

Reputation: 7930

You can use ZeroMQ, there is an excellent Python binding called pyzmq. It is a library for writing all kinds of distributed software, based on the concept of message queues. The project got a lot of hype lately, and you will find numerous examples and tutorials on the web.

Upvotes: 1

Related Questions