服务端(发布端):
using System;
using NetMQ;
using NetMQ.Sockets;
namespace WeatherUpdateServer
{
internal static class WeatherUpdateServer
{
private static void Main()
{
Console.Title = "NetMQ Weather Update Server";
bool stopRequested = false;
// Wire up the CTRL+C handler
Console.CancelKeyPress += (sender, e) => stopRequested = true;
Console.WriteLine("Publishing weather updates...");
using (var publisher = new PublisherSocket())
{
publisher.Bind("tcp://127.0.0.1:5556");
var rng = new Random();
while (!stopRequested)
{
int zipcode = rng.Next(0, 99999);
int temperature = rng.Next(-80, 135);
int relhumidity = rng.Next(0, 90);
publisher.SendFrame($"{zipcode} {temperature} {relhumidity}");
}
}
}
}
}
客户端(接收端):
using System;
using System.Globalization;
using NetMQ;
using NetMQ.Sockets;
namespace WeatherUpdateClient
{
internal static class WeatherUpdateClient
{
private static void Main()
{
Console.Title = "NetMQ Weather Update Client";
const int zipToSubscribeTo = 10001;
const int iterations = 100;
int totalTemp = 0;
int totalHumidity = 0;
Console.WriteLine("Collecting updates for weather service for zipcode {0}...", zipToSubscribeTo);
using (var subscriber = new SubscriberSocket())
{
subscriber.Connect("tcp://127.0.0.1:5556");
subscriber.Subscribe(zipToSubscribeTo.ToString(CultureInfo.InvariantCulture));
for (int i = 0; i < iterations; i++)
{
string results = subscriber.ReceiveFrameString();
Console.Write(".");
// "zip temp relh" ... "10001 84 23" -> ["10001", "84", "23"]
string[] split = results.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int zip = int.Parse(split[0]);
if (zip != zipToSubscribeTo)
{
throw new Exception($"Received message for unexpected zipcode: {zip} (expected {zipToSubscribeTo})");
}
totalTemp += int.Parse(split[1]);
totalHumidity += int.Parse(split[2]);
}
}
Console.WriteLine();
Console.WriteLine("Average temperature was: {0}", totalTemp/iterations);
Console.WriteLine("Average relative humidity was: {0}", totalHumidity/iterations);
}
}
}
运行结果:
总结:
1、最基本的发布订阅模型。
2、服务端通过绑定地址后,随机发送一串数字文本如 ["10001", "84", "23"],客户端通过Subscribe(string topic) 设置 topic 接收字符串前缀过滤信息。
3、绑定的地址不能重复绑定,客户端连接数可以为多个。
4、服务端只发不收,客户端只收不发。
5、服务端如连不上客户端地址不会报错,connect后进入阻塞。