简体   繁体   English

通过网络发送字符串

[英]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. 我想要两个进程使用send()和receive()函数相互发送字符串(消息)。 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). 我知道使用裸流套接字非常容易,但这仍然很麻烦且容易出错(在循环内执行多个conn.recv()并检查大小,例如HTTP或流结束标记,例如SMTP等)。

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? 难道没有一个简单的库(Twisted AMP看起来并不简单)做到这一点吗? I've been searching the Internet for a few hours without success :) 我已经在互联网上搜索了几个小时,但没有成功:)

You can use ZeroMQ , there is an excellent Python binding called pyzmq . 您可以使用ZeroMQ ,有一个出色的Python绑定称为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. 最近,该项目大肆宣传,您将在网络上找到大量示例和教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM