Beispiel #1
0
    /// <summary>
    /// 套接字循环, 在背景线程中运行
    /// </summary>
    private void SocketLoop()
    {
#if UNITY_EDITOR
        // use this to avoid freeze when reload script with (a) scenes running
        UnityEditor.AssemblyReloadEvents.beforeAssemblyReload += ClearSocket;
#endif
        // 初始化AsyncIO
        AsyncIO.ForceDotNet.Force();
        terminated = false;
        using (socket = new PullSocket(ConfigManager.instance.Current.mazeEditorAddress))
        {
            try
            {
                FrameStringProcess(socket.ReceiveFrameString());
                while (!terminated)
                {
                    FrameStringProcess(socket.ReceiveFrameString());
                }
            }
            catch (TerminatingException)
            {
                Debug.Log("Socket terminated.");
            }
            finally
            {
                socket.Dispose();
                NetMQConfig.Cleanup();
            }
        }
    }
Beispiel #2
0
        /// <summary>
        ///     This is called when a new historical data request or data push request is made.
        /// </summary>
        private void SocketReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            string requesterIdentity;
            string text;

            lock (_socketLock)
            {
                // Here we process the first two message parts: first, the identity string of the client
                requesterIdentity = _socket?.ReceiveFrameString() ?? string.Empty;
                // Second: the string specifying the type of request
                text = _socket?.ReceiveFrameString() ?? string.Empty;
            }

            if (text.Equals(MessageType.HistRequest, StringComparison.InvariantCultureIgnoreCase)) // The client wants to request some data
            {
                AcceptHistoricalDataRequest(requesterIdentity);
            }
            else if (text.Equals(MessageType.HistPush, StringComparison.InvariantCultureIgnoreCase)) // The client wants to push some data into the db
            {
                AcceptDataAdditionRequest(requesterIdentity);
            }
            else if (text.Equals(MessageType.AvailableDataRequest, StringComparison.InvariantCultureIgnoreCase)) // Client wants to know what kind of data we have stored locally
            {
                AcceptAvailableDataRequest(requesterIdentity);
            }
            else
            {
                _logger.Info($"Unrecognized request to historical data broker: {text}");
            }
        }
        public static Message ReceiveMessage(this NetMQSocket socket)
        {
            var identifier    = socket.ReceiveFrameIdentifier();
            var hmac          = socket.ReceiveFrameString();
            var headerFrame   = socket.ReceiveFrameString();
            var parentFrame   = socket.ReceiveFrameString();
            var metadataFrame = socket.ReceiveFrameString();
            var contentFrame  = socket.ReceiveFrameString();

            if (!Validator.IsValidSignature(hmac, headerFrame, parentFrame, metadataFrame, contentFrame))
            {
                return(null);
            }

            var     header = JsonConvert.DeserializeObject <Header>(headerFrame);
            Content content;

            switch (header.MessageType)
            {
            case MessageType.ExecuteRequest:
                content = JsonConvert.DeserializeObject <ExecuteRequestContent>(contentFrame);
                break;

            case MessageType.CompleteRequest:
                content = JsonConvert.DeserializeObject <CompleteRequestContent>(contentFrame);
                break;

            case MessageType.ShutDownRequest:
                content = JsonConvert.DeserializeObject <ShutdownContent>(contentFrame);
                break;

            case MessageType.KernelInfoRequest:
                content = JsonConvert.DeserializeObject <Content>(contentFrame);
                break;
            //case MessageType.ExecuteInput:
            //case MessageType.ExecuteReply:
            //case MessageType.ExecuteResult:
            //case MessageType.CompleteReply:
            //case MessageType.ShutDownReply:
            //case MessageType.KernelInfoReply:

            //case MessageType.Status:
            //case MessageType.Output:
            //case MessageType.Input:
            //case MessageType.Error:
            //case MessageType.Stream:
            default:
                Logger?.LogWarning(header.MessageType + " message not handled.");
                content = new Content();
                break;
            }

            // Update the static session
            SessionId = header.Session;

            return(new Message(header.MessageType, content, JsonConvert.DeserializeObject <Header>(parentFrame),
                               identifier, header, hmac, JsonConvert.DeserializeObject <Dictionary <string, object> >(metadataFrame)));
        }
        private void RequestSocketReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            lock (_requestConnectionString)
            {
                if (_requestSocket != null)
                {
                    var requestType = _requestSocket.ReceiveFrameString();

                    if (requestType == null)
                    {
                        return;
                    }
                    // Handle ping requests
                    if (requestType.Equals(MessageType.Ping, StringComparison.InvariantCultureIgnoreCase))
                    {
                        _requestSocket.SendFrame(MessageType.Pong);

                        return;
                    }
                    // Handle real time data requests
                    if (requestType.Equals(MessageType.RTDRequest, StringComparison.InvariantCultureIgnoreCase)) // Two part message: first, "RTD" string. Then the RealTimeDataRequest object.
                    {
                        HandleRealTimeDataRequest();
                    }
                    // Manage cancellation requests
                    // Three part message: first: MessageType.CancelRTD. Second: the instrument ID. Third: frequency.
                    if (requestType.Equals(MessageType.CancelRTD, StringComparison.InvariantCultureIgnoreCase))
                    {
                        HandleRealTtimeDataCancelRequest();
                    }
                }
            }
        }
Beispiel #5
0
        /// <summary>
        ///     This is called when a new historical data request or data push request is made.
        /// </summary>
        private void SocketReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            string requesterIdentity;
            DataRequestMessageType type;

            lock (socketLock)
            {
                // Here we process the first two message parts: first, the identity string of the client
                requesterIdentity = socket.ReceiveFrameString() ?? string.Empty;
                // Second: the string specifying the type of request
                type = (DataRequestMessageType)BitConverter.ToInt16(socket.ReceiveFrameBytes(), 0);
            }

            switch (type)
            {
            case DataRequestMessageType.HistPush:
                AcceptDataAdditionRequest(requesterIdentity);
                break;

            case DataRequestMessageType.HistRequest:
                AcceptHistoricalDataRequest(requesterIdentity);
                break;

            case DataRequestMessageType.AvailableDataRequest:
                AcceptAvailableDataRequest(requesterIdentity);
                break;

            default:
                logger.Info($"Unrecognized request to historical data broker: {type}");
                break;
            }
        }
Beispiel #6
0
        public static Message GetMessage(this NetMQSocket socket)
        {
            var message = new Message();

            // There may be additional ZMQ identities attached; read until the delimiter <IDS|MSG>"
            // and store them in message.identifiers
            // http://ipython.org/ipython-doc/dev/development/messaging.html#the-wire-protocol
            var delimiterAsBytes = Encoding.ASCII.GetBytes(Constants.DELIMITER);

            while (true)
            {
                var delimiter = socket.ReceiveFrameBytes();
                if (delimiter.SequenceEqual(delimiterAsBytes))
                {
                    break;
                }
                message.Identifiers.Add(delimiter);
            }

            // Getting Hmac
            message.Signature = socket.ReceiveFrameString();

            // Getting Header
            var header = socket.ReceiveFrameString();

            message.Header = JsonConvert.DeserializeObject <Header>(header);

            // Getting parent header
            var parentHeader = socket.ReceiveFrameString();

            message.ParentHeader = JsonConvert.DeserializeObject <Header>(parentHeader);

            // Getting metadata
            var metadata = socket.ReceiveFrameString();

            message.MetaData = JObject.Parse(metadata);

            // Getting content
            var content = socket.ReceiveFrameString();

            message.Content = JObject.Parse(content);

            return(message);
        }
Beispiel #7
0
        public static Message GetMessage(this NetMQSocket socket)
        {
            // There may be additional ZMQ identities attached; read until the delimiter <IDS|MSG>"
            // and store them in message.identifiers
            // http://ipython.org/ipython-doc/dev/development/messaging.html#the-wire-protocol
            var delimiterAsBytes = Encoding.ASCII.GetBytes(Constants.DELIMITER);

            var identifiers = new List <byte[]>();

            while (true)
            {
                var delimiter = socket.ReceiveFrameBytes();
                if (delimiter.SequenceEqual(delimiterAsBytes))
                {
                    break;
                }
                identifiers.Add(delimiter);
            }

            // Getting Hmac
            var signature = socket.ReceiveFrameString();

            // Getting Header
            var headerJson = socket.ReceiveFrameString();

            // Getting parent header
            var parentHeaderJson = socket.ReceiveFrameString();

            // Getting metadata
            var metadataJson = socket.ReceiveFrameString();

            // Getting content
            var contentJson = socket.ReceiveFrameString();

            var message = DeserializeMessage(signature, headerJson, parentHeaderJson, metadataJson, contentJson, identifiers);

            return(message);
        }
Beispiel #8
0
        private static void Server(NetMQContext context)
        {
            using (NetMQSocket serverSocket = context.CreateResponseSocket())
            {
                serverSocket.Bind("tcp://127.0.0.1:5555");
                while (true)
                {
                    string message1 = serverSocket.ReceiveFrameString();

                    Console.WriteLine("Receive message :\r\n{0}\r\n", message1);

                    string[] msg     = message1.Split(':');
                    string   message = msg[1];


                    #region 根据接收到的消息,返回不同的信息
                    if (message == "Hello")
                    {
                        serverSocket.SendFrame("World");
                    }
                    else if (message == "ni hao ")
                    {
                        serverSocket.SendFrame("你好!");
                    }
                    else if (message == "hi")
                    {
                        serverSocket.SendFrame("HI");
                    }
                    else
                    {
                        serverSocket.SendFrame(message);
                    }
                    #endregion



                    if (message == "exit")
                    {
                        break;
                    }
                }
            }
        }
Beispiel #9
0
        static void Server(NetMQContext context)
        {
            using (NetMQSocket serverSocket = context.CreateResponseSocket())
            {
                serverSocket.Bind("tcp://*:5555");

                while (true)
                {
                    string message = serverSocket.ReceiveFrameString();

                    Console.WriteLine("Receive message {0}", message);

                    serverSocket.SendFrame("World");

                    if (message == "exit")
                    {
                        break;
                    }
                }
            }
        }
Beispiel #10
0
        static void Client(NetMQContext context)
        {
            using (NetMQSocket clientSocket = context.CreateRequestSocket())
            {
                clientSocket.Connect("tcp://127.0.0.1:5555");

                while (true)
                {
                    Console.WriteLine("Please enter your message:");
                    string message = Console.ReadLine();
                    clientSocket.SendFrame(message);

                    string answer = clientSocket.ReceiveFrameString();

                    Console.WriteLine("Answer from server: {0}", answer);

                    if (message == "exit")
                    {
                        break;
                    }
                }
            }
        }
Beispiel #11
0
        public void OnDataReady()
        {
            switch (m_state)
            {
            case WebSocketClientState.Closed:
                m_state = WebSocketClientState.Handshake;
                string clientHandshake = m_streamSocket.ReceiveFrameString();

                string[] lines = clientHandshake.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                string key;

                if (ValidateClientHandshake(lines, out key))
                {
                    string acceptKey = GenerateAcceptKey(key);

                    try
                    {
                        if (m_streamSocket.TrySendFrame(Identity, Identity.Length, true) &&
                            m_streamSocket.TrySendFrame("HTTP/1.1 101 Switching Protocols\r\n" +
                                                        "Upgrade: websocket\r\n" +
                                                        "Connection: Upgrade\r\n" +
                                                        "Sec-WebSocket-Accept: " + acceptKey + "\r\n" +
                                                        "Sec-WebSocket-Protocol: WSNetMQ\r\n\r\n"))
                        {
                            m_decoder          = new Decoder();
                            m_decoder.Message += OnMessage;
                            m_state            = WebSocketClientState.Ready;
                        }
                        else
                        {
                            m_state = WebSocketClientState.Closed;
                        }
                    }
                    catch (NetMQException)
                    {
                        m_state = WebSocketClientState.Closed;
                    }
                }
                else
                {
                    m_state = WebSocketClientState.Closed;

                    if (m_streamSocket.TrySendFrame(Identity, Identity.Length, true))
                    {
                        m_streamSocket.TrySendFrame("HTTP/1.1 400 Bad Request\r\nSec-WebSocket-Version: 13\r\n");
                    }

                    // invalid request, close the socket and raise closed event
                    if (m_streamSocket.TrySendFrame(Identity, Identity.Length, true))
                    {
                        m_streamSocket.TrySendFrame("");
                    }
                }

                break;

            case WebSocketClientState.Ready:
                byte[] message = m_streamSocket.ReceiveFrameBytes();
                m_decoder.Process(message);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }