Beispiel #1
0
        public void Do()
        {
            // we are using dealer here, but we can use router as well, we just have to manager
            // SecureChannel for each identity
            using (var socket = new DealerSocket())
            {
                socket.Bind("tcp://*:9696");

                using (SecureChannel secureChannel = SecureChannel.CreateServerSecureChannel(m_configuration))
                {
                    // we need to set X509Certificate with a private key for the server
                    X509Certificate2 certificate = new X509Certificate2(
                        System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.pfx"), "1234");
                    secureChannel.Certificate = certificate;

                    List <NetMQMessage> outgoingMessages = new List <NetMQMessage>();

                    // waiting for message from client
                    NetMQMessage incomingMessage = socket.ReceiveMultipartMessage();
                    //SplitInMessage

                    // calling ProcessMessage until ProcessMessage return true
                    // and the SecureChannel is ready to encrypt and decrypt messages
                    while (!secureChannel.ProcessMessage(incomingMessage, outgoingMessages))
                    {
                        //SendMessages(socket,outgoingMessages);
                        foreach (NetMQMessage message in outgoingMessages)
                        {
                            socket.SendMultipartMessage(message);
                        }
                        outgoingMessages.Clear();
                        incomingMessage = socket.ReceiveMultipartMessage();
                    }
                    //SendMessages(socket, outgoingMessages);
                    foreach (NetMQMessage message in outgoingMessages)
                    {
                        socket.SendMultipartMessage(message);
                    }
                    outgoingMessages.Clear();

                    // this message is now encrypted
                    NetMQMessage cipherMessage = socket.ReceiveMultipartMessage();

                    // decrypting the message
                    NetMQMessage plainMessage = secureChannel.DecryptApplicationMessage(cipherMessage);
                    System.Console.WriteLine(plainMessage.First.ConvertToString());
                    plainMessage = new NetMQMessage();
                    plainMessage.Append("Worldddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");

                    // encrypting the message and sending it over the socket
                    socket.SendMultipartMessage(secureChannel.EncryptApplicationMessage(plainMessage));
                }
            }
        }
        public void RouterDealerMessaging()
        {
            using (var server = new RouterSocket())
                using (var client = new DealerSocket())
                {
                    int port = server.BindRandomPort("tcp://127.0.0.1");
                    client.Connect("tcp://127.0.0.1:" + port);

                    var clientOutgoingMessage = new NetMQMessage();
                    clientOutgoingMessage.Append("Hello");

                    client.SendMultipartMessage(clientOutgoingMessage);

                    NetMQMessage serverIncomingMessage = server.ReceiveMultipartMessage();

                    // number of frames should be one because first message should be identity of client
                    Assert.Equal(2, serverIncomingMessage.FrameCount);
                    Assert.Equal("Hello", serverIncomingMessage[1].ConvertToString());

                    var serverOutgoingMessage = new NetMQMessage();

                    // first adding the identity
                    serverOutgoingMessage.Append(serverIncomingMessage[0]);
                    serverOutgoingMessage.Append("World");

                    server.SendMultipartMessage(serverOutgoingMessage);

                    var incomingClientMessage = client.ReceiveMultipartMessage();

                    Assert.Equal(1, incomingClientMessage.FrameCount);
                    Assert.Equal("World", incomingClientMessage[0].ConvertToString());
                }
        }
Beispiel #3
0
        private string SendRequest(string request)
        {
            using (var server = new DealerSocket())
            {
                server.Options.Identity = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());

                var ok = false;
                do
                {
                    try
                    {
                        server.Connect($"{_serverEndpoint}");
                        ok = true;
                    }
                    catch (NetMQException ex)
                    {
                    }
                } while (!ok);


                var msg = new NetMQMessage();
                msg.AppendEmptyFrame();
                msg.Append(request);

                server.SendMultipartMessage(msg);

                var result = server.ReceiveMultipartMessage();

                return(result[1].ConvertToString());
            }
        }
Beispiel #4
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Klijent");
            Console.WriteLine("Unesite nick");
            string nick          = Console.ReadLine();
            string message       = string.Empty;
            string sendMessageTo = Console.ReadLine();

            using (var dealer = new DealerSocket())
            {
                dealer.Connect("tcp://127.0.0.1:5555");

                dealer.Options.Identity = Encoding.ASCII.GetBytes(nick);
                while (true)
                {
                    message = Console.ReadLine();
                    var msgToSrv = new NetMQMessage();
                    msgToSrv.Append(message);
                    msgToSrv.Append(nick);
                    dealer.SendMultipartMessage(msgToSrv);
                    //dealer.SendFrame(message);
                    var receiveFromServer = dealer.ReceiveMultipartMessage();
                    Console.WriteLine(receiveFromServer);
                }
            }
        }
            public void Send(String message)
            {
                using (var server = new DealerSocket())
                {
                    server.Options.Identity = Encoding.UTF8.GetBytes("CLIENT");

                    var ok = false;
                    do
                    {
                        try
                        {
                            server.Connect(_serverEndpoint);
                            ok = true;
                            Task.Delay(1000);
                        }
                        catch (NetMQException ex)
                        {
                        }
                    } while (!ok);


                    var msg = new NetMQMessage();
                    msg.AppendEmptyFrame();
                    msg.Append(message);

                    server.SendMultipartMessage(msg);

                    var result = server.ReceiveMultipartMessage();

                    var te = result[0];
                }
            }
Beispiel #6
0
        private static void Client()
        {
            using (var sender = new DealerSocket())
            {
                sender.Options.Identity = Encoding.Unicode.GetBytes("salda".ToString());
                sender.Connect("tcp://127.0.0.1:9045");
                while (true)
                {
                    var message = new NetMQMessage();
                    message.Append("hello");
                    sender.SendMultipartMessage(message);
                    Console.WriteLine("Sent request");
                    //var response = sender.ReceiveMultipartMessage();
                    //Console.WriteLine("Received response");
                    //var itr = response.GetEnumerator();
                    //Console.WriteLine($"{(itr.MoveNext() ? "found" : "didn't find")} greeting frame");
                    //Console.WriteLine($"Greeting is: {itr.Current.ConvertToString()}");

                    var receiveFrameBytes = sender.ReceiveMultipartMessage();
                    using (var ms = new MemoryStream())
                    {
                        var equity = ProtoBufDeserialize <Equity>(receiveFrameBytes[0].Buffer, ms);
                        Console.WriteLine($"Equity: {equity.Value}");
                    }


                    Thread.Sleep(TimeSpan.FromSeconds(5));
                }
            }
        }
Beispiel #7
0
        public static KeyData DealerReceive(this DealerSocket socket)
        {
            KeyData kd = new KeyData();

            NetMQMessage msg = socket.ReceiveMultipartMessage();

            kd.Key  = msg[1].ConvertToString();
            kd.Data = msg[2].Buffer;

            return(kd);
        }
        private Task Synchronize()
        {
            _getMarketState.SendFrame(StateRequest.Default.Serialize());

            var enveloppe = _getMarketState.ReceiveMultipartMessage()
                            .GetMessageFromPublisher <StateReply <TDto> >();

            Updates.Clear();

            foreach (var update in enveloppe.Message.Updates)
            {
                Updates.Add(update.Position, update);
            }

            _resetEvent.Set();

            return(Task.CompletedTask);
        }
Beispiel #9
0
        private void OnBackEndReady(object sender, NetMQSocketEventArgs e)
        {
            NetMQMessage message = _backendSocket.ReceiveMultipartMessage();

            _frontendSocket.SendMultipartMessage(message);
        }
Beispiel #10
0
        public async Task <bool> RunSimulationAsync(Options options, TextWriter logger, CancellationToken token = default)
        {
            Logger = logger;
            try {
                Id = options.Id;

                _socket = new DealerSocket();
                _socket.Options.Linger   = TimeSpan.FromSeconds(30);
                _socket.Options.Identity = Encoding.ASCII.GetBytes(Id);
                if (options.Connect)
                {
                    _socket.Connect(options.URL);
                }
                else
                {
                    _socket.Bind(options.URL);
                }

                using (Outgoing = new NetMQQueue <NetMQMessage>()) {
                    using var poller = new NetMQPoller()
                          {
                              _socket, Outgoing
                          };
                    _socket.ReceiveReady += (sender, e) => {
                        var msg = _socket.ReceiveMultipartMessage();
                        if (msg.FrameCount < 3)
                        {
                            logger.WriteLine($"Received message with only {msg.FrameCount} frames.");
                            return;
                        }
                        var type = msg[1].ConvertToString();
                        logger.WriteLine($"Received {type} message.");
                        switch (type)
                        {
                        case "crane":
                            OnCraneMessageReceived(msg[2].Buffer);
                            break;

                        case "sim":
                            OnSimMessageReceived(msg[2].Buffer);
                            break;

                        default: //Console.WriteLine($"Received message with unmapped type {type}");
                            break;
                        }
                    };
                    Outgoing.ReceiveReady += (sender, e) => {
                        var msg = Outgoing.Dequeue();
                        if (_socket.TrySendMultipartMessage(TimeSpan.FromMinutes(1), msg)) // Note that for policyruns (virtual time) a lot of events are generated
                        {
                            logger.WriteLine($"Sent {msg[1].ConvertToString()} message.");
                        }
                        //else logger.WriteLine($"Discarded outgoing {msg[1].ConvertToString()} message.");
                    };

                    if (!options.RunSync || options.Connect)
                    {
                        poller.RunAsync();
                    }

                    if (!string.IsNullOrEmpty(options.SettingsPath))
                    {
                        if (options.SettingsPath.Equals("Default", StringComparison.OrdinalIgnoreCase))
                        {
                            logger.WriteLine("Using default settings");
                            _settingsReceived.SetResult(GetDefaultSettings());
                        }
                        else
                        {
                            logger.WriteLine($"Reading settings from {options.SettingsPath}");
                            _settingsReceived.SetResult(File.ReadAllBytes(options.SettingsPath));
                        }
                    }
                    var result = false;
                    try {
                        if (!options.RunSync)
                        {
                            result = await RunSimulationAsync(await _settingsReceived.Task, options.PolicyRun);

                            // wait until the outgoing queue is cleared
                            var remaining = Outgoing.Count;
                            while (remaining > 0)
                            {
                                await Task.Delay(1000, token);

                                if (Outgoing.Count == remaining)
                                {
                                    break;              // assume nobody is listening for world states
                                }
                                remaining = Outgoing.Count;
                            }
                        }
                        else
                        {
                            result = RunSimulation(await _settingsReceived.Task, options.SyncURL, options.Id);
                        }
                    } finally {
                        poller.Stop();
                    }
                    return(result);
                }
            } finally {
                DisposeSocket();
            }
        }
Beispiel #11
0
        public void Receive()
        {
            ReceiveDataManager manager = new ReceiveDataManager();

            while (true)
            {
                try
                {
                    var    mQFrames = dealer.ReceiveMultipartMessage(6);
                    byte[] mory     = mQFrames.Last.ToByteArray();
                    MSG    revmsg   = ProtoBufHelp.DeSerialize <MSG>(mory);
                    //消息来源
                    var fromId = mQFrames[3].ConvertToString();
                    var toId   = mQFrames[4].ConvertToString();
                    if (revmsg == null)
                    {
                        continue;
                    }
                    if (revmsg.type == MSG.Type.ALGORITHM || revmsg.type == MSG.Type.DEVICE || revmsg.type == MSG.Type.STATUS || revmsg.type == MSG.Type.CREW)
                    {
                        var component = ProtoBDManager.GetComponentById(fromId);
                        if (component == null)
                        {
                            //记录从陆地端传过来的ID,船舶端发送时做为上级ID传值
                            ManagerHelp.UpToId = fromId;
                        }
                    }
                    if (revmsg.type == MSG.Type.COMPONENT)
                    {
                        manager.ComponentData(revmsg.component);
                    }
                    if (revmsg.type == MSG.Type.ALARM)
                    {
                        if (revmsg.alarm.alarminfo != null)
                        {
                            string xmq = "";
                            //陆地端收到船舶推送的报警数据带有upload标识
                            //船舶端收到陆地端的响应带有request标识
                            if (mQFrames[2].ConvertToString() == "upload" || mQFrames[2].ConvertToString() == "request")
                            {
                                xmq = fromId;
                            }
                            manager.AlarmData(xmq, revmsg.alarm.alarminfo);
                            //var ss = new ProtoBDManager();
                            //ss.AlarmAdd(revmsg.alarm.alarminfo, xmq);
                        }
                    }
                    else if (revmsg.type == MSG.Type.EVENT)
                    {
                        if (revmsg.evt != null)
                        {
                            string xmqId = "";
                            if (mQFrames[2].ConvertToString() == "upload")
                            {
                                xmqId = fromId;
                            }
                            manager.EventData(revmsg.evt, xmqId);
                        }
                    }
                    Task.Factory.StartNew(st =>
                    {
                        try
                        {
                            if (revmsg.type == MSG.Type.ALGORITHM)
                            {
                                manager.AlgorithmData(revmsg.algorithm, fromId);
                            }
                            else if (revmsg.type == MSG.Type.CREW)
                            {
                                manager.CrewData(revmsg.crew);
                            }
                            else if (revmsg.type == MSG.Type.DEVICE)
                            {
                                manager.DeviceData(revmsg.device);
                            }
                            else if (revmsg.type == MSG.Type.STATUS)
                            {
                                manager.StatusData(revmsg.status);
                            }
                        }
                        catch (Exception ex)
                        {
                            //异常日志入库
                            ProtoBDManager.AddReceiveLog <MSG>("Exception", revmsg, ex.Message);
                        }
                    }, TaskCreationOptions.LongRunning);
                }
                catch (Exception ex)
                {
                    //异常日志入库
                    ProtoBDManager.AddReceiveLog("Exception", "数据处理异常", ex.Message);
                    continue;
                }
                Thread.Sleep(100);
            }
        }
Beispiel #12
0
        public void Do()
        {
            using (var socket = new DealerSocket())
            {
                socket.Connect("tcp://127.0.0.1:5556");

                SecureChannel secureChannel = SecureChannel.CreateClientSecureChannel(null, m_configuration);

                // we are not using signed certificate so we need to validate
                // the certificate of the server, by default the secure channel
                // is checking that the source of the
                // certitiface is a root certificate authority
                //secureChannel.SetVerifyCertificate(c => true);

                // we need to set X509Certificate with a private key for the server
                X509Certificate2 certificate = new X509Certificate2(
                    System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.crt"), "1234");
                secureChannel.Certificate = certificate;

                List <NetMQMessage> outgoingMessages = new List <NetMQMessage>();

                // call the process message with null as the incoming message
                // because the client is initiating the connection
                secureChannel.ProcessMessage(null, outgoingMessages);
                //Server.SendMessages(socket, outgoingMessages);

                foreach (NetMQMessage message in outgoingMessages)
                {
                    socket.SendMultipartMessage(message);
                }
                outgoingMessages.Clear();
                // waiting for a message from the server
                NetMQMessage incomingMessage = socket.ReceiveMultipartMessage();

                // calling ProcessMessage until ProcessMessage return true
                // and the SecureChannel is ready to encrypt and decrypt messages
                while (!secureChannel.ProcessMessage(incomingMessage, outgoingMessages))
                {
                    foreach (NetMQMessage message in outgoingMessages)
                    {
                        socket.SendMultipartMessage(message);
                    }
                    outgoingMessages.Clear();
                    //Server.SendMessages(socket, outgoingMessages);
                    incomingMessage = socket.ReceiveMultipartMessage();
                }

                foreach (NetMQMessage message in outgoingMessages)
                {
                    socket.SendMultipartMessage(message);
                }
                outgoingMessages.Clear();
                //Server.SendMessages(socket, outgoingMessages);
                // you can now use the secure channel to encrypt messages
                NetMQMessage plainMessage = new NetMQMessage();
                plainMessage.Append("Hello");

                // encrypting the message and sending it over the socket
                socket.SendMultipartMessage(secureChannel.EncryptApplicationMessage(plainMessage));
                NetMQMessage cipherMessage = socket.ReceiveMultipartMessage();

                // decrypting the message
                plainMessage = secureChannel.DecryptApplicationMessage(cipherMessage);
                System.Console.WriteLine(plainMessage.First.ConvertToString());
            }
        }