private void HandleWork() { using (var stateUpdate = new SubscriberSocket()) { stateUpdate.SubscribeToAnyTopic(); stateUpdate.Bind(_configuration.ToPublisherEndpoint); using (var stateUpdatePublish = new PublisherSocket()) { stateUpdatePublish.Bind(_configuration.ToSubscribersEndpoint); stateUpdate.ReceiveReady += async(s, e) => { var message = e.Socket.ReceiveMultipartMessage(); var subject = message[0].ConvertToString(); var payload = message[1]; var eventId = await _cache.AppendToStream(subject, payload.Buffer); stateUpdatePublish.SendMoreFrame(message[0].Buffer) .SendMoreFrame(_serializer.Serialize(eventId)) .SendFrame(payload.Buffer); }; using (_poller = new NetMQPoller { stateUpdate, stateUpdatePublish }) { _poller.Run(); } } } }
public static void Main(string[] args) { const int MegaBit = 1024; const int MegaByte = 1024; using (var pub = new PublisherSocket()) using (var sub1 = new SubscriberSocket()) using (var sub2 = new SubscriberSocket()) { pub.Options.MulticastHops = 2; pub.Options.MulticastRate = 40 * MegaBit; // 40 megabit pub.Options.MulticastRecoveryInterval = TimeSpan.FromMinutes(10); pub.Options.SendBuffer = MegaByte * 10; // 10 megabyte pub.Connect("pgm://224.0.0.1:5555"); sub1.Options.ReceiveBuffer = MegaByte * 10; sub1.Bind("pgm://224.0.0.1:5555"); sub1.Subscribe(""); sub2.Bind("pgm://224.0.0.1:5555"); sub2.Options.ReceiveBuffer = MegaByte * 10; sub2.Subscribe(""); Console.WriteLine("Server sending 'Hi'"); pub.SendFrame("Hi", false); bool more; Console.WriteLine("sub1 received = '{0}'", sub1.ReceiveFrameString(out more)); Console.WriteLine("sub2 received = '{0}'", sub2.ReceiveFrameString(out more)); } }
private void Run() { using var publisher = new PublisherSocket(); publisher.Bind(@"tcp://127.0.0.1:17232"); using var subscriber = new SubscriberSocket(); subscriber.Bind(@"tcp://127.0.0.1:17233"); subscriber.SubscribeToAnyTopic(); running.Set(); using var server = new TelnetServer(IPAddress.Any, port, publisher, subscriber) { OptionReuseAddress = true }; Log.Information("Server starting ..."); server.Start(); while (running.WaitOne(TimeSpan.Zero)) { if (subscriber.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(100), out var frame)) { server.Multicast(frame); } } server.Stop(); Log.Information("Server stopped."); }
public void LargeMessage() { using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { pub.Connect("pgm://224.0.0.1:5555"); sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); var data = new byte[3200]; // this should be at least 3 packets for (Int16 i = 0; i < 1600; i++) { Array.Copy(BitConverter.GetBytes(i), 0, data, i * 2, 2); } pub.SendFrame(data); byte[] message = sub.ReceiveFrameBytes(); Assert.AreEqual(3200, message.Length); for (Int16 i = 0; i < 1600; i++) { Assert.AreEqual(i, BitConverter.ToInt16(message, i * 2)); } } }
public void TwoPublishers() { using (var pub = new PublisherSocket()) using (var pub2 = new PublisherSocket()) using (var sub = new SubscriberSocket()) { pub.Connect("pgm://224.0.0.1:5555"); pub2.Connect("pgm://224.0.0.1:5555"); sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); pub.SendFrame("Hi"); bool more; Assert.AreEqual("Hi", sub.ReceiveFrameString(out more)); Assert.IsFalse(more); pub2.SendFrame("Hi2"); Assert.AreEqual("Hi2", sub.ReceiveFrameString(out more)); Assert.IsFalse(more); } }
public void SetPgmSettings() { const int MegaBit = 1024; const int MegaByte = 1024; using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { pub.Options.MulticastHops = 2; pub.Options.MulticastRate = 40 * MegaBit; // 40 megabit pub.Options.MulticastRecoveryInterval = TimeSpan.FromMinutes(10); pub.Options.SendBuffer = MegaByte * 10; // 10 megabyte pub.Connect("pgm://224.0.0.1:5555"); sub.Options.ReceiveBuffer = MegaByte * 10; sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); pub.SendFrame("Hi"); bool more; Assert.AreEqual("Hi", sub.ReceiveFrameString(out more)); Assert.IsFalse(more); Assert.AreEqual(2, pub.Options.MulticastHops); Assert.AreEqual(40 * MegaBit, pub.Options.MulticastRate); Assert.AreEqual(TimeSpan.FromMinutes(10), pub.Options.MulticastRecoveryInterval); Assert.AreEqual(MegaByte * 10, pub.Options.SendBuffer); Assert.AreEqual(MegaByte * 10, sub.Options.ReceiveBuffer); } }
public void SubsriberCleanupOnUnbind(string address) { for (var i = 0; i < 10; i++) { using (var sub = new SubscriberSocket()) { sub.Bind(address); using (var monitor = new NetMQMonitor(sub, String.Format("inproc://cleanup.test{0}", Guid.NewGuid()), SocketEvents.Closed)) { var monitorTask = Task.Factory.StartNew(monitor.Start); var closed = new ManualResetEventSlim(); monitor.Closed += (sender, args) => closed.Set(); var time = DateTime.Now; sub.Unbind(address); Assert.That(closed.Wait(1000), Is.True, "Unbind failed to report Closed event to the Monitor"); var duration = DateTime.Now - time; Console.WriteLine("Run {0}: {1} ms", i, duration.TotalMilliseconds); monitor.Stop(); monitorTask.Wait(); } } } }
public void UseInterface() { #if NETCOREAPP1_0 var hostEntry = Dns.GetHostEntryAsync(Dns.GetHostName()).Result; #else var hostEntry = Dns.GetHostEntry(Dns.GetHostName()); #endif string ip = hostEntry.AddressList .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork) .Select(addr => addr.ToString()) .FirstOrDefault(); using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { pub.Connect($"pgm://{ip};224.0.0.1:5555"); sub.Bind($"pgm://{ip};224.0.0.1:5555"); sub.Subscribe(""); pub.SendFrame("Hi"); bool more; Assert.AreEqual("Hi", sub.ReceiveFrameString(out more)); Assert.IsFalse(more); } }
public (bool success, Exception ex) Setup() { Exception exception = null; try { _socketDelegate = async(s, arg) => await HandleAsync(); _socket.ReceiveReady += _socketDelegate; // todo use actual topics instead of catchall string catchAllTopic = ""; _socket.Bind(_configuration.Address()); _socket.Subscribe(catchAllTopic); _configuration.Logger.Log(new DebugLogMsg($"subscribed to [{typeof(TMessage)}]")); _poller.Add(_socket); _poller.RunAsync(); return(true, null); } catch (NetMQ.EndpointNotFoundException ntfnd) { _configuration.Logger.Log(new ErrorLogMsg(ntfnd.Message)); exception = ntfnd; return(false, exception); } }
public void Sending1000Messages() { // creating two different context and sending 1000 messages int count = 0; var subReady = new ManualResetEvent(false); Task subTask = Task.Factory.StartNew(() => { using (var sub = new SubscriberSocket()) { sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); subReady.Set(); while (count < 1000) { bool more; Assert.AreEqual(count, BitConverter.ToInt32(sub.ReceiveFrameBytes(out more), 0)); Assert.IsFalse(more); count++; } } }); subReady.WaitOne(); Task pubTask = Task.Factory.StartNew(() => { using (var pub = new PublisherSocket()) { pub.Connect("pgm://224.0.0.1:5555"); for (int i = 0; i < 1000; i++) { pub.SendFrame(BitConverter.GetBytes(i)); } // if we close the socket before the subscriber receives all messages subscriber // might miss messages, lets wait another second Thread.Sleep(1000); } }); pubTask.Wait(); subTask.Wait(); Thread.MemoryBarrier(); Assert.AreEqual(1000, count); }
static void Main(string[] args) { //using (var server = new ResponseSocket("@tcp://localhost:5556")) // bind //using (var client = new RequestSocket(">tcp://localhost:5556")) // connect //{ // // Send a message from the client socket // client.SendFrame("Hello"); // // Receive the message from the server socket // string m1 = server.ReceiveFrameString(); // Console.WriteLine("From Client: {0}", m1); // // Send a response back from the server // server.SendFrame("Hi Back"); // // Receive the response from the client socket // string m2 = client.ReceiveFrameString(); // Console.WriteLine("From Server: {0}", m2); //} const int MegaBit = 1024; const int MegaByte = 1024; using (var pub = new PublisherSocket()) using (var sub1 = new SubscriberSocket()) using (var sub2 = new SubscriberSocket()) { pub.Options.MulticastHops = 2; pub.Options.MulticastRate = 40 * MegaBit; // 40 megabit pub.Options.MulticastRecoveryInterval = TimeSpan.FromMinutes(10); pub.Options.SendBuffer = MegaByte * 10; // 10 megabyte pub.Connect("pgm://224.0.0.1:5555"); sub1.Options.ReceiveBuffer = MegaByte * 10; sub1.Bind("pgm://224.0.0.1:5555"); sub1.Subscribe(""); sub2.Bind("pgm://224.0.0.1:5555"); sub2.Options.ReceiveBuffer = MegaByte * 10; sub2.Subscribe(""); Console.WriteLine("Server sending 'Hi'"); pub.Send("Hi"); bool more; Console.WriteLine("sub1 received = '{0}'", sub1.ReceiveString(out more)); Console.WriteLine("sub2 received = '{0}'", sub2.ReceiveString(out more)); } Console.ReadLine(); }
private static void Main(string[] args) { var deciSecond = new TimeSpan(10000); using (var subscriber = new SubscriberSocket()) // For receiving updates from presentation host using (var publisher = new WSPublisher()) // For publishing updates from presentation host to audience using (var responder = new WSRouter()) // Handling on-demand requests for late-joining or crashing clients { subscriber.Bind("tcp://*:3000"); subscriber.SubscribeToAnyTopic(); publisher.Bind("ws://*:3001"); responder.Bind("ws://*:3002"); byte step = 0; subscriber.ReceiveReady += (_, __) => { if (!subscriber.TryReceiveFrameBytes(deciSecond, out var received)) { return; } step = received[0]; Console.Out.WriteLine("Sending " + step + " to audience."); publisher.TrySendFrame(deciSecond, new[] { step }); }; responder.ReceiveReady += (_, __) => { NetMQMessage msg = null; if (!responder.TryReceiveMultipartMessage(deciSecond, ref msg)) { return; } var identity = msg.Pop().Buffer; var request = msg.Pop().ConvertToString(); msg.Clear(); if (request == "Which slide are we on?") { responder.TrySendMultipartBytes(deciSecond, identity, new[] { step }); } else { if (!responder.TrySendFrame(deciSecond, identity, true)) { return; } responder.TrySendFrameEmpty(deciSecond); } }; new NetMQPoller { subscriber, responder }.Run(); // Polling both subscriber and router sockets. } }
public void Start() { _publishStateUpdate = new PublisherSocket(); _publishStateUpdate.Bind(_brokerConfiguration.PublishUpdatesEndpoint); _subscribeToUpdates = new SubscriberSocket(); _subscribeToUpdates.SubscribeToAnyTopic(); _subscribeToUpdates.Bind(_brokerConfiguration.SubscribeToUpdatesEndpoint); _stateRequest = new RouterSocket(); _stateRequest.Bind(_brokerConfiguration.SendStateEndpoint); _workProc = Task.Run(DoStart, _cancel.Token).ConfigureAwait(false); _heartBeartProc = Task.Run(HandleHeartbeat, _cancel.Token).ConfigureAwait(false); }
private void HandleWork() { using (var stateUpdate = new SubscriberSocket()) { stateUpdate.SubscribeToAnyTopic(); stateUpdate.Bind(_configuration.ToPublisherEndpoint); stateUpdate.Options.ReceiveHighWatermark = _configuration.ZmqHighWatermark; using (var stateUpdatePublish = new PublisherSocket()) { stateUpdatePublish.Bind(_configuration.ToSubscribersEndpoint); stateUpdate.ReceiveReady += async(s, e) => { try { NetMQMessage message = null; while (e.Socket.TryReceiveMultipartMessage(ref message)) { var subject = message[0]; var payload = message[1]; stateUpdatePublish.SendMoreFrame(subject.Buffer) .SendMoreFrame(_serializer.Serialize(await _cache.AppendToStream(subject.Buffer, payload.Buffer))) .SendFrame(payload.Buffer); } } catch (Exception ex) { Errors.Add(new ActorMonitoringError() { CacheErrorStatus = ActorErrorType.DynamicCacheEventHandlingFailure, Exception = ex }); } }; using (_workPoller = new NetMQPoller { stateUpdate, stateUpdatePublish }) { _workPoller.Run(); } } } }
public void BindBothSockets() { using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { pub.Bind("pgm://224.0.0.1:5555"); sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); pub.SendFrame("Hi"); Assert.AreEqual("Hi", sub.ReceiveFrameString(out bool more)); Assert.IsFalse(more); } }
/// <summary> /// Starts the local to external message transfering. /// </summary> /// <param name="proxyForPublishersPort">The port for local publishers.</param> /// <param name="busPublisherPort">Broker's publisher port for other brokers subscription.</param> private void StartLocalToExternalTransfer(int proxyForPublishersPort, int busPublisherPort) { Task.Run(() => { using (var subSocket = new SubscriberSocket()) using (var pubSocket = new PublisherSocket()) { subSocket.SubscribeToAnyTopic(); subSocket.Bind($"tcp://localhost:{proxyForPublishersPort}"); pubSocket.Bind($"tcp://localhost:{busPublisherPort}"); _localToExternalProxy = new NetMQ.Proxy(subSocket, pubSocket); _localToExternalProxy.Start(); } }); }
/// <summary> /// Creates a new instance of the <see cref="DualSocketBus"/> type. /// </summary> /// <param name="endpoint"> The message bus' endpoint. </param> /// <param name="dispatcher"> The dispatcher that is used for incoming and outgoing messages. </param> protected DualSocketBus(IDualSocketEndpoint endpoint, ISocketDispatcherThread dispatcher) { Endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); Dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); IncomingMessages = new Lazy <SubscriberSocket>(() => { var incomingMessages = new SubscriberSocket(); incomingMessages.SubscribeToAnyTopic(); incomingMessages.Bind(Endpoint.Incoming); incomingMessages.ReceiveReady += OnIncomingMessagesReceived; return(incomingMessages); }, true); OutgoingMessages = new Lazy <PublisherSocket>(() => { var outgoingMessages = new PublisherSocket(); outgoingMessages.Bind(Endpoint.Outgoing); return(outgoingMessages); }, true); }
private void TaskClientAudioSub(CancellationToken cancelToken, BlockingCollection <ClientAudio> outputQueue, string bind) { using (var subSocket = new SubscriberSocket()) { subSocket.Options.ReceiveHighWatermark = 50; subSocket.Bind(bind); subSocket.Subscribe(""); while (!cancelToken.IsCancellationRequested) { var clientID = subSocket.ReceiveFrameString(); var audioData = subSocket.ReceiveFrameBytes(); serverStatistics.AudioBytesReceived += audioData.Length; outputQueue.Add(new ClientAudio() { Callsign = clientID, Data = audioData }); } taskClientDataSub = null; } }
private void TaskClientDataSub(CancellationToken cancelToken, BlockingCollection <object> queue, string bind) { using (var subSocket = new SubscriberSocket()) { subSocket.Options.ReceiveHighWatermark = 50; subSocket.Bind(bind); subSocket.Subscribe(""); while (!cancelToken.IsCancellationRequested) { var messageTopicReceived = subSocket.ReceiveFrameString(); int bytesReceived = 0; switch (messageTopicReceived) { case "ClientHeartbeat": ClientHeartbeat clientHeartbeat = subSocket.Deserialise <ClientHeartbeat>(out bytesReceived); serverStatistics.DataBytesReceived += bytesReceived; CheckAndAddIfNewClient(clientHeartbeat); break; case "ClientPositionUpdate": ClientPositionUpdate clientPositionUpdate = subSocket.Deserialise <ClientPositionUpdate>(out bytesReceived); serverStatistics.DataBytesReceived += bytesReceived; CheckAndAddIfNewClient(clientPositionUpdate); UpdateMobileClientPosition(clientPositionUpdate); break; case "ClientFrequencyUpdate": ClientFrequencyUpdate clientFrequencyUpdate = subSocket.Deserialise <ClientFrequencyUpdate>(out bytesReceived); serverStatistics.DataBytesReceived += bytesReceived; CheckAndAddIfNewClient(clientFrequencyUpdate); UpdateMobileClientFrequency(clientFrequencyUpdate); break; } } taskClientDataSub = null; } }
private void SetupFakeBroker( CancellationToken cancel, IEventCache eventCache, bool useHeartbeat = true, bool useEventLoop = true, bool useStateOfTheWorld = true) { if (useHeartbeat) { //heartbeat Task.Run(() => { using (var heartbeatSocket = new ResponseSocket(HeartbeatEndpoint)) { while (!cancel.IsCancellationRequested) { var hasResponse = heartbeatSocket.TryReceiveFrameBytes(TimeSpan.FromSeconds(1), out var messageBytes); if (hasResponse) { heartbeatSocket.SendFrame(_serializer.Serialize(Heartbeat.Response)); } } } }, cancel); } if (useEventLoop) { //event loop Task.Run(async() => { using (var stateUpdate = new SubscriberSocket()) { stateUpdate.SubscribeToAnyTopic(); stateUpdate.Bind(ToPublishersEndpoint); while (!cancel.IsCancellationRequested) { NetMQMessage message = null; var hasResponse = stateUpdate.TryReceiveMultipartMessage(TimeSpan.FromSeconds(1), ref message); if (hasResponse) { var subject = message[0]; var payload = message[1]; await eventCache.AppendToStream(subject.Buffer, payload.Buffer); } } } }, cancel); } if (useStateOfTheWorld) { //stateOfTheWorld Task.Run(async() => { using (var stateRequestSocket = new RouterSocket()) { stateRequestSocket.Bind(StateOfTheWorldEndpoint); while (!cancel.IsCancellationRequested) { NetMQMessage message = null; var hasResponse = stateRequestSocket.TryReceiveMultipartMessage(TimeSpan.FromSeconds(1), ref message); if (hasResponse) { var sender = message[0].Buffer; var request = _serializer.Deserialize <StateRequest>(message[1].Buffer); var stream = await eventCache.GetStreamBySubject(request.Subject); var response = new StateReply() { Subject = request.Subject, Events = stream.ToList() }; stateRequestSocket.SendMoreFrame(sender) .SendFrame(_serializer.Serialize(response)); } } } }, cancel); } }
protected override void OnStart(SubscriberSocket socket) { socket.Bind(_address); }
public OCForm() { sc = WindowsFormsSynchronizationContext.Current as WindowsFormsSynchronizationContext; InitializeComponent(); flowLayoutPanelSysmenu.MouseDown += MoveWindow; flowLayoutPanelSysmenu.DoubleClick += ResizeWindow; toolStripLeftPanel.MouseDown += MoveWindow; toolStripLeftPanel.DoubleClick += ResizeWindow; RegisterSysCommandBehavior(); RegisterOwnerDraw(); LoadLeftPanel(); //Random randomGen = new Random(); //KnownColor[] names = (KnownColor[])Enum.GetValues(typeof(KnownColor)); lvConversations.Items.AddRange(new ListViewItem[] { new ListViewItem("1") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "姓名1", LastUpdate = DateTime.Now, PeekMessage = "Message1", IsMute = true } }, new ListViewItem("2") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name2", LastUpdate = DateTime.Now, PeekMessage = "\ue136", IsMute = true } }, new ListViewItem("3") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name3", LastUpdate = DateTime.Now, PeekMessage = "消息~3", IsMute = true } }, new ListViewItem("1") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "姓名1", LastUpdate = DateTime.Now, PeekMessage = "Message1", IsMute = true } }, new ListViewItem("2") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name2", LastUpdate = DateTime.Now, PeekMessage = "\ue137", IsMute = true } }, new ListViewItem("3") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name3", LastUpdate = DateTime.Now, PeekMessage = "消息~3", IsMute = true } }, new ListViewItem("1") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "姓名1", LastUpdate = DateTime.Now, PeekMessage = "Message1", IsMute = true } }, new ListViewItem("2") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name2", LastUpdate = DateTime.Now, PeekMessage = "Message2", IsMute = true } }, new ListViewItem("3") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name3", LastUpdate = DateTime.Now, PeekMessage = "消息~3", IsMute = true } }, new ListViewItem("1") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "姓名1", LastUpdate = DateTime.Now, PeekMessage = "\ue138", IsMute = true } }, new ListViewItem("2") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name2", LastUpdate = DateTime.Now, PeekMessage = "Message2", IsMute = true } }, new ListViewItem("3") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name3", LastUpdate = DateTime.Now, PeekMessage = "消息~3", IsMute = true } }, new ListViewItem("1") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "姓名1", LastUpdate = DateTime.Now, PeekMessage = "Message1", IsMute = true } }, new ListViewItem("2") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name2", LastUpdate = DateTime.Now, PeekMessage = "\ue139", IsMute = true } }, new ListViewItem("3") { Tag = new ConversationShortcut() { Icon = Guid.NewGuid(), DisplayName = "Name3", LastUpdate = DateTime.Now, PeekMessage = "消息~3", IsMute = true } }, }); for (int i = 0; i < lvConversations.Items.Count; i++) { var shortcut = lvConversations.Items[i].Tag as ConversationShortcut; var chatUI = GetChatUI(shortcut.Icon); chatrooms.AddOrUpdate(shortcut.Icon.ToString(), chatUI, (key, value) => chatUI); //chatUI.BackColor = Color.FromKnownColor(names[randomGen.Next(names.Length)]); } /*chatUI.AddMessage(Guid.Empty, "你好,祝你生日快乐!"); * chatUI.AddMessage(Guid.Empty, "你是?", false); * chatUI.AddMessage(Guid.Empty, "我是你的小号啊"); * chatUI.AddMessage(Guid.Empty, ":-( 伐开熏 ...", false); */ Messaging.Message message = null; ThreadPool.QueueUserWorkItem(state => { //Get Message From 0MQ //Handle bool working = true; while (working) { sendEvent.WaitOne(); //Validate Message; if (message != null) { Guid guid = message.From; string Guid = guid.ToString(); ChatUI ui = null; if (chatrooms.ContainsKey(Guid)) { ui = chatrooms[Guid]; } else { ui = new ChatUI(guid); chatrooms.TryAdd(Guid, ui); } } } }); ThreadPool.QueueUserWorkItem(state => { using (SubscriberSocket subscriber = new SubscriberSocket()) { subscriber.Bind($"tcp://localhost:12555"); //Handle Subscriber subscriber.SubscribeToAnyTopic(); Msg msg = new Msg(); msg.InitEmpty(); while (true) { subscriber.TryReceive(ref msg, TimeSpan.MaxValue); using (MemoryStream ms = new MemoryStream(msg.Data)) { BinaryFormatter bf = new BinaryFormatter(); Messaging.Message groupMessage = bf.Deserialize(ms) as Messaging.Message; if (groupMessage == null) { continue; } if (!groupMessage.MessageType.HasFlag(Messaging.MessageType.MT_GROUP_FLAG)) { continue; } Guid from = groupMessage.From; } } } }); ThreadPool.QueueUserWorkItem(state => { new FakeServer().Init(); }); cmdSend.Click += (sender, @event) => { if (ActiveChatUI == null) { return; } Guid TO = ActiveChatUI.Target; string to = TO.ToString(); if (!members.ContainsKey(to)) { return; } using (var client = new RequestSocket()) { Messaging.Membership membership = members[to]; client.Connect($">tcp://0x{membership.LastLoginIP:X}:12553"); string ____ = "-------------------"; byte[] data = Encoding.UTF8.GetBytes(____); Messaging.Message m = new Messaging.Message(1, from, TO, Guid.Empty, TimeSpan.FromMinutes(1D), false, new Guid(), Messaging.MessageType.MT_PLAINTEXT, data.Length, data); using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, m); data = ms.ToArray(); msg.Put(data, 0, data.Length); } client.Send(ref msg, false); //Clear Input sendEvent.Set(); } }; lvConversations.Click += (sender, @event) => { if (lvConversations.SelectedIndices.Count == 0) { return; } int selectedIndex = lvConversations.SelectedIndices[0]; var shortcut = lvConversations.Items[selectedIndex].Tag as ConversationShortcut; if (shortcut == null) { return; } ChatUI chatUI = GetChatUI(shortcut.Icon); for (int i = 0; i < splitContainerChat.Panel1.Controls.Count; i++) { splitContainerChat.Panel1.Controls[i].Visible = (chatUI == splitContainerChat.Panel1.Controls[i]); } ActiveChatUI = chatUI; lblInfo.Text = shortcut.DisplayName; }; lblInfo.Click += (sender, @event) => { Msg m = new Msg();// m.InitEmpty(); Messaging.Message _message = MessageFactory.CreateMemberInfoMessage(new Guid(), new Guid(), new Guid()); byte[] b = SerializerUtil <Messaging.Message> .Serialize(_message); m.InitPool(b.Length); m.Put(b, 0, b.Length); using (var client = new RequestSocket()) { client.Connect("tcp://localhost:12553"); client.Send(ref m, false); Msg mm = new Msg(); mm.InitEmpty(); client.Receive(ref mm); var reply = SerializerUtil <Messaging.Message> .Deserialize(mm.Data); var response = SerializerUtil <MemberInfoResponse> .Deserialize(reply.Content); var membership = response.Membership; MessageBox.Show($"{membership.ID}\n{membership.Name}\n{membership.NickName}\n0x{membership.LastLoginIP :X08}"); } }; }