4

1つのサーバーから複数のクライアントにメッセージを送信するようにプログラムしようとしました。クライアント側ではC#を使用し、サーバー側ではC++を使用する必要があります。サーバーのhttp://zguide.zeromq.org/page:all#toc8から例を取りました。

#define within(num) (int) ((float) num * rand () / (RAND_MAX + 1.0))

int main () {

//  Prepare our context and publisher
zmq::context_t context (1);
zmq::socket_t publisher (context, ZMQ_PUB);
publisher.bind("tcp://*:5556");
//publisher.bind("ipc://weather.ipc");

//  Initialize random number generator
srand ((unsigned) time (NULL));
while (1) {

    int zipcode, temperature, relhumidity;

    //  Get values that will fool the boss
    zipcode     = within (100000);
    temperature = within (215) - 80;
    relhumidity = within (50) + 10;

    //  Send message to all subscribers
    zmq::message_t message(20);
    _snprintf ((char *) message.data(), 20 ,
        "%05d %d %d", zipcode, temperature, relhumidity);
    publisher.send(message);

}
return 0;
}

そしてクライアントのために:

namespace ZMQGuide
{
internal class Program
{
    public static void Main(string[] args) {
        Console.WriteLine("Collecting updates from weather server…");

        // default zipcode is 10001
        string zipcode = "10001 "; // the reason for having a space after 10001 is in case of the message would start with 100012 which we are not interested in

        if (args.Length > 0)
            zipcode = args[1] + " ";

        using (var context = new Context(1))
        {
            using (Socket subscriber = context.Socket(SocketType.SUB))
            {
                subscriber.Subscribe(zipcode, Encoding.Unicode);
                subscriber.Connect("tcp://localhost:5556");

                const int updatesToCollect = 100;
                int totalTemperature = 0;

                for (int updateNumber = 0; updateNumber < updatesToCollect; updateNumber++)
                {
                    string update = subscriber.Recv(Encoding.Unicode);
                    totalTemperature += Convert.ToInt32(update.Split()[1]);
                }

                Console.WriteLine("Average temperature for zipcode {0} was {1}F", zipcode, totalTemperature / updatesToCollect);
            }
        }
    }
}
}

彼らはお互いに通信しません。クライアント側(C ++)では、Windowsクライアントでipcが失敗したため、ipcインタラクションで行にコメントしました。この場合、C#-C#、C++-C++の相互作用は正しく機能します。clrzmq2.2.5を使用します。

助けていただければ幸いです。

4

1 に答える 1

7

C#クライアントは、2バイトのUnicode表現(UTF-16)であるEncoding.Unicodeを使用しています。C++サーバーはASCIIを使用しています。

ZMQサブスクリプションマッチングはバイトレベルで機能し、文字エンコード間で変換されないため、これが私の問題です。C#クライアントでEncoding.ASCIIまたはEncoding.UTF8に切り替えると、この問題は解決します。

于 2012-08-22T13:09:31.073 に答える