コード例 #1
0
 public void RequestReply()
 {
     ThreadPool.QueueUserWorkItem(state =>
     {
         var server = new ResponseSocket();
         server.Bind("tcp://*:5555");
         while (!_stopLoops)
         {
             try
             {
                 var receiveFrame = server.ReceiveFrameBytes();
                 var request      = Serializer.Deserialize <Request>(new MemoryStream(receiveFrame));
                 var response     = OnRequest(request);
                 using (var responseStream = new MemoryStream())
                 {
                     Serializer.Serialize(responseStream, response);
                     server.SendFrame(responseStream.ToArray());
                 }
             }
             catch (Exception e)
             {
                 Console.WriteLine(e);
             }
         }
     });
 }
コード例 #2
0
        private void EventLoop()
        {
            var addr = context.ConnectionInfo.HeartbeatZmqAddress;

            this.logger.LogDebug("Starting heartbeat server at {Address}.", addr);
            socket = new ResponseSocket();
            socket.Bind(addr);

            while (alive)
            {
                // We use the Bytes receiver so that we can ping back data
                // unmodified, without worrying about encodings.
                try
                {
                    var data = socket.ReceiveFrameBytes();
                    logger.LogDebug($"Got heartbeat message of length {data.Length}.");
                    if (!socket.TrySendFrame(data))
                    {
                        logger.LogError("Error sending heartbeat message back to client.");
                    }
                }
                catch (ThreadInterruptedException)
                {
                    continue;
                }
                catch (Exception ex)
                {
                    logger.LogCritical(ex, "Unhandled exception in heartbeat loop.");
                }
            }
        }
コード例 #3
0
 public void StartRsp(int port)
 {
     using (var server = new ResponseSocket("@tcp://localhost:5556"))// bind
     {
         byte[] m1 = server.ReceiveFrameBytes();
         Console.WriteLine("From Client: {0}", m1);
         // server.SendFrame
         // Send a response back from the server
         server.SendFrame("Hi Back");
     }
 }
コード例 #4
0
ファイル: Program.cs プロジェクト: AlekseySyryh/ZeroMQTest
 static void Main(string[] args)
 {
     using (var server = new ResponseSocket())
     {
         server.Bind("tcp://*:5555");
         while (true)
         {
             var data = server.ReceiveFrameBytes();
             Console.WriteLine($"Received {data.Length} bytes");
             server.SendFrame(new byte[1]);
         }
     }
 }
コード例 #5
0
        private void StartServerLoop(object state)
        {
            _socket.Bind(_address);

            while (!_stopEvent.Wait(0))
            {
                byte[] data = _socket.ReceiveFrameBytes();

                _logger.LogInformation(System.Text.Encoding.Default.GetString(data));
                // Echoing back whatever was received
                _socket.TrySendFrame(data);
            }
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: arseniybanayev/CSharpDim
        private static void StartHeartbeatLoop(string heartbeatAddress)
        {
            HeartbeatSocket.Bind(heartbeatAddress);

            while (!StopEvent.Wait(0))
            {
                var data = HeartbeatSocket.ReceiveFrameBytes();

                Log.Info(Encoding.Default.GetString(data));
                // Echoing back whatever was received
                HeartbeatSocket.TrySendFrame(data);
            }
        }
コード例 #7
0
        public void HeartBeat()
        {
            using (_heartbeat = new ResponseSocket(_heartbeatEndpoint))
            {
                while (!_cancel.IsCancellationRequested)
                {
                    var heartbeatQuery = _heartbeat.ReceiveFrameBytes()
                                         .Deserialize <Heartbeat>();

                    _heartbeat.SendFrame(Heartbeat.Response.Serialize());
                }
            }
        }
コード例 #8
0
ファイル: LazyPirateServer.cs プロジェクト: iennacca/lhotse
        public void Respond(Func <TextRequest, TextResponse> callback)
        {
            var server = new ResponseSocket();

            server.Bind(Address.OriginalString);
            while (true)
            {
                var bRequest = server.ReceiveFrameBytes();
                var sRequest = Encoding.Unicode.GetString(bRequest);

                var sReturn = callback(new TextRequest(sRequest));
                var bReturn = Encoding.Unicode.GetBytes(sReturn.Text);
                server.SendFrame(bReturn);
            }
        }
コード例 #9
0
 public void Start(string address)
 {
     using (ResponseSocket responseSocket = new ResponseSocket("@tcp://" + address))
     {
         while (true)
         {
             byte[]       buf          = responseSocket.ReceiveFrameBytes();
             TCPUserToken tCPUserToken = new TCPUserToken
             {
                 Data   = buf,
                 Socket = responseSocket
             };
             queue.Add(tCPUserToken);
         }
     }
 }
コード例 #10
0
        public void HandleHeartbeat()
        {
            using (_heartbeatSocket = new ResponseSocket(_configuration.HeartbeatEndpoint))
            {
                while (!_cancel.IsCancellationRequested)
                {
                    var messageBytes = _heartbeatSocket.ReceiveFrameBytes();

                    if (_cancel.IsCancellationRequested)
                    {
                        return;
                    }

                    _heartbeatSocket.SendFrame(_serializer.Serialize(Heartbeat.Response));
                }
            }
        }
コード例 #11
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await Task.Yield();

            _server.Bind(_address);

            using (Logger <Heartbeat> .Log.OnEnterAndExit())
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    var data = _server.ReceiveFrameBytes();

                    // Echoing back whatever was received
                    _server.TrySendFrame(data);
                }
            }
        }
コード例 #12
0
        private static void ListenForSocketRequests()
        {
            _socketServer = new ResponseSocket(Ipc.RepoZIpcEndpoint.Address);

            while (true)
            {
                bool hasMore;
                var  load = _socketServer.ReceiveFrameBytes(out hasMore);

                string message = Encoding.UTF8.GetString(load);

                if (string.IsNullOrEmpty(message))
                {
                    return;
                }

                if (message.StartsWith("list:", StringComparison.Ordinal))
                {
                    string repositoryNamePattern = message.Substring("list:".Length);

                    string answer = "(no repositories found)";
                    try
                    {
                        var aggregator = TinyIoCContainer.Current.Resolve <IRepositoryInformationAggregator>();
                        var repos      = aggregator.Repositories
                                         .Where(r => string.IsNullOrEmpty(repositoryNamePattern) || Regex.IsMatch(r.Name, repositoryNamePattern, RegexOptions.IgnoreCase))
                                         .Select(r => $"{r.Name}|{r.BranchWithStatus}|{r.Path}")
                                         .ToArray();

                        if (repos.Any())
                        {
                            answer = string.Join(Environment.NewLine, repos);
                        }
                    }
                    catch (Exception ex)
                    {
                        answer = ex.Message;
                    }

                    _socketServer.SendFrame(Encoding.UTF8.GetBytes(answer));
                }

                Thread.Sleep(100);
            }
        }
コード例 #13
0
        public void HandleHeartbeat()
        {
            using (_heartbeat = new ResponseSocket(_brokerConfiguration.HeartbeatEndpoint))
            {
                while (!_cancel.IsCancellationRequested)
                {
                    var heartbeatQuery = _heartbeat.ReceiveFrameBytes()
                                         .Deserialize <Heartbeat>();

                    if (_cancel.IsCancellationRequested)
                    {
                        return;
                    }

                    _heartbeat.SendFrame(Heartbeat.Response.Serialize());
                }
            }
        }
コード例 #14
0
 static void Main(string[] args)
 {
     using (var commandreceiver = new ResponseSocket("@tcp://*:5555"))
     {
         while (true)
         {
             var msg = commandreceiver.ReceiveFrameBytes();
             using (var stream = new MemoryStream(msg))
             {
                 CreateAccount command = Serializer.Deserialize <CreateAccount>(stream);
                 //Serializer.Deserialize<string>(stream);
                 Console.WriteLine("id = " + command.AccountId + " holder name = " + command.HolderName);
                 commandreceiver.SendFrame(new AccountCreated(new Guid(), "test").ToString());
                 //return
             }
         }
     }
 }
コード例 #15
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _server.Bind(_address);
            Task.Run(() =>
            {
                using (Logger <Heartbeat> .Log.OnEnterAndExit())
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        var data = _server.ReceiveFrameBytes();

                        // Echoing back whatever was received
                        _server.TrySendFrame(data);
                    }
                }
            }, cancellationToken);

            return(Task.CompletedTask);
        }
コード例 #16
0
ファイル: Node.cs プロジェクト: thomasraynal/ZeroMQPlayground
        public void Start()
        {
            using (_heartbeat = new ResponseSocket(_endpoint))
            {
                while (!_cancel.IsCancellationRequested)
                {
                    var messageBytes = _heartbeat.ReceiveFrameBytes();
                    var message      = JsonConvert.DeserializeObject <HeartbeatQuery>(Encoding.UTF8.GetString(messageBytes));

                    var response = new HeartbeatResponse()
                    {
                        Endpoint = _endpoint
                    };

                    var responseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response));

                    _heartbeat.SendFrame(responseBytes);
                }
            }
        }
コード例 #17
0
        public void Start(CancellationToken cancellationToken)
        {
            using (_activeResponder = new ResponseSocket())
            {
                // Bind
                _activeResponder.Bind(_activeEndPoint);

                _running = true;

                while (_running && !cancellationToken.IsCancellationRequested)
                {
                    try
                    {
                        // Receive
                        byte[] request = _activeResponder.ReceiveFrameBytes();

                        MessageFrame <THeader, TPayload> messageFrame = MessageSerializer.Deserialize <MessageFrame <THeader, TPayload> >(request);

                        if (ReceiveMessage != null)
                        {
                            MessageFrame <THeader, TPayload> reply = ReceiveMessage(messageFrame.MessageType, messageFrame.Payload);

                            // Do some work
                            Thread.Sleep(1);

                            // Send
                            _activeResponder.SendFrame(MessageSerializer.ObjectToByteArray(reply), false);
                        }
                    }
                    catch (Exception)
                    {
                        if (_running)
                        {
                            throw;
                        }
                    }
                }
            }

            _activeResponder = null;
        }
コード例 #18
0
        public void HandleHeartbeat()
        {
            using (_heartbeat = new ResponseSocket(_configuration.HeartbeatEndpoint))
            {
                while (!_cancel.IsCancellationRequested)
                {
                    var heartbeatQuery = _heartbeat.ReceiveFrameBytes()
                                         .Deserialize <Heartbeat>();

                    if (heartbeatQuery.Descriptor.ActorType == ActorType.Worker)
                    {
                        if (_registeredWorkers.TryGetValue(heartbeatQuery.Descriptor.ActorId, out var worker))
                        {
                            worker.LastHeartbeat = DateTime.Now;
                        }
                    }

                    _heartbeat.SendFrame(this.GetHeartbeat(HeartbeatType.Pong).Serialize());
                }
            }
        }
コード例 #19
0
        public static async Task <int> Main(string[] args)
        {
            if (args.Length != 1)
            {
                await Console.Error.WriteLineAsync("Please specify the server name!");

                return(1);
            }
            string serverName = args[0];

            using (ResponseSocket server = new ResponseSocket())
            {
                await Console.Out.WriteLineAsync($"Starting server '{serverName}'");

                Message message = new Message();
                message.Name = serverName;

                server.Bind("tcp://localhost:5556");
                while (true)
                {
                    byte[]  reply    = server.ReceiveFrameBytes();
                    Message replyMsg = Message.Parser.ParseFrom(reply);

                    await Console.Out.WriteLineAsync($"{replyMsg.ShowString()}");

                    message.Timestamp = DateTime.UtcNow.Ticks;
                    message.Body      = "thank you";

                    await Console.Out.WriteLineAsync($"{message.ShowString()}");

                    byte[] serverMsg = message.ToByteArray();
                    server.SendFrame(serverMsg);

                    //Thread.Sleep(5000);
                }
            }
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: zhouji0212/Samples
        private static void Main()
        {
            Console.Title = "NetMQ LazyPirate Server";

            const string serverEndpoint = "tcp://127.0.0.1:5555";

            var random = new Random();

            using (var server = new ResponseSocket())
            {
                Console.WriteLine("S: Binding address {0}", serverEndpoint);
                server.Bind(serverEndpoint);

                var cycles = 0;

                while (true)
                {
                    byte[] request = server.ReceiveFrameBytes();
                    cycles++;

                    if (cycles > 3 && random.Next(0, 10) == 0)
                    {
                        Console.WriteLine("S: Simulating a crash");
                        Thread.Sleep(5000);
                    }
                    else if (cycles > 3 && random.Next(0, 10) == 0)
                    {
                        Console.WriteLine("S: Simulating CPU overload");
                        Thread.Sleep(1000);
                    }

                    Console.WriteLine("S: Normal request ({0})", Encoding.Unicode.GetString(request));
                    server.SendFrame(request);
                }
            }
        }
コード例 #21
0
ファイル: ByteServer.cs プロジェクト: hukaidong/CrowdComm
 public byte[] Recv_Byte()
 {
     return(socket.ReceiveFrameBytes());
 }
コード例 #22
0
        public void TryRunning()
        {
            try {
                RefreshOpenTasks();
                using (var responseSocket = new ResponseSocket()) {
                    _logger.Info("Started the server", _threadId);
                    responseSocket.Bind(_settings.ServerIP);
                    DateTime lastRefresh = DateTime.Now;
                    while (_settings.ContinueRunning)
                    {
                        if (AutomaticRefresh && (DateTime.Now - lastRefresh).TotalMinutes > 3 && OpenTasks.Count < 500)
                        {
                            lastRefresh = DateTime.Now;
                            RefreshOpenTasks();
                        }

                        try {
                            _logger.Info("Waiting for frame", _threadId);
                            var requestBytes = responseSocket.ReceiveFrameBytes();
                            if (!_settings.ContinueRunning)
                            {
                                _logger.Info("don't continue received, quitting server...", _threadId);
                                return;
                            }

                            string prettySize = AutomationUtili.MakePrettySize(requestBytes.Length);
                            _logger.Info("received a byte[] with a length of " + prettySize, _threadId);
                            MessageFromClientToServer req;
                            try {
                                req = LZ4MessagePackSerializer.Deserialize <MessageFromClientToServer>(requestBytes);
                            }
                            catch (Exception ex) {
                                _logger.Exception(ex, "failed to deserialize string with  " + requestBytes.Length + " bytes", _threadId);
                                AnswerRequest(responseSocket,
                                              new MessageFromServerToClient(ServerResponseEnum.NothingToDo, Guid.NewGuid().ToString()));
                                continue;
                            }

                            _logger.Info("Received: " + req.ClientName + ": " + req.ClientRequest + " ## ", _threadId);
                            MessageFromServerToClient answer;

                            // ReSharper disable once SwitchStatementMissingSomeCases
                            _clients.TrackLastRequest(req);
                            switch (req.ClientRequest)
                            {
                            case ClientRequestEnum.RequestForJob:
                                answer = HandleRequestForJob(req);
                                break;

                            case ClientRequestEnum.ReportFinish:
                                answer = HandleTaskFinishReport(req);
                                break;

                            case ClientRequestEnum.ReportFailure:
                                answer = HandleFailureReport(req);
                                break;

                            case ClientRequestEnum.RequestForLPGFiles:
                                answer = HandleRequestForLpgFiles(req);
                                break;

                            case ClientRequestEnum.ReportDiskspaceFull:
                                answer = HandleDiskFullReport(req);
                                break;

                            default:
                                _logger.Error("Invalid client request: " + req.ClientRequest, _threadId);
                                AnswerRequest(responseSocket,
                                              new MessageFromServerToClient(ServerResponseEnum.NothingToDo, "no idea what you want"));
                                throw new DistSimException("Invalid request");
                            }

                            _logger.Info("Sent: " + req.ClientName + ": " + answer.ServerResponse, _threadId);
                            AnswerRequest(responseSocket, answer);
                            _clients.TrackLastAnswer(req.ClientName, answer);
                        }
                        catch (Exception ex) {
                            ThreadException = ex;
                            _logger.Exception(ex, "Exception in the server thread inner loop: \n" + ex.StackTrace);
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex) {
                ThreadException = ex;
                _logger.Exception(ex, "Exception in the server thread: \n");
                throw;
            }
        }