Exemple #1
0
        static async Task RunViaSockets()
        {
            using (var server = new SimplSocketServer(
                       () => new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = true
            }))
            {
                server.MessageReceived += (s, e) =>
                {
                    var blob = e.ReceivedMessage.Message;
                    ReverseServer.Reverse(blob);
                    server.Reply(blob, e.ReceivedMessage);
                };

                server.Listen(new IPEndPoint(IPAddress.Loopback, 5000));
                await Console.Out.WriteLineAsync(
                    "Server running; type 'q' to exit, anything else to broadcast");

                string line;
                while ((line = await Console.In.ReadLineAsync()) != null)
                {
                    if (line == "q")
                    {
                        break;
                    }

                    var blob = Encoding.UTF8.GetBytes(line);
                    server.Broadcast(blob);

                    await Console.Out.WriteLineAsync(
                        $"Broadcast {blob.Length} bytes to {server.CurrentlyConnectedClientCount} clients");
                }
            }
        }
        public void Reply <TIn>(string identifier, TIn message, ReceivedMessage receivedMessage)
        {
            var rawMessage = _serializer.Serialize <TIn>(identifier, message);

            if (rawMessage == null)
            {
                return;
            }
            _simplSocketServer.Reply(rawMessage, receivedMessage.Socket, receivedMessage.ThreadId);
        }
Exemple #3
0
        void CreateServer()
        {
            // Create the server
            var server = new SimplSocketServer();

            // Create a callback for received array
            server.MessageReceived += (s, e) =>
            {
                // Get the message
                var receivedMessage = e.ReceivedMessage;
                Console.WriteLine($"Server received message of {receivedMessage.Length} bytes");

                // Reply to the message with the same message (echo)
                server.Reply(receivedMessage, receivedMessage);
                Console.WriteLine($"Server replied to message");


                // We cannot not dispose the received message directly, since it may still need to be send
                // Instead we use the ReturnAfterSend, which will return the message to the pool after sending
                receivedMessage.ReturnAfterSend();
            };
            // Start listening for client connections on loopback endpoint
            server.Listen(new IPEndPoint(IPAddress.Loopback, 5000));
        }