예제 #1
0
        public static void Execute()
        {
            Console.WriteLine("Executing ReqRep test");

            const string inprocAddress = "inproc://reqrep_test";

            byte[] buffer1;
            byte[] buffer2;

            var clientThread = new Thread(
                () => {
                var req = NN.Socket(Domain.SP, Protocol.REQ);
                NN.Connect(req, inprocAddress);
                NN.Send(req, BitConverter.GetBytes((int)42), SendRecvFlags.NONE);
                NN.Recv(req, out buffer1, SendRecvFlags.NONE);
                Debug.Assert(BitConverter.ToInt32(buffer1, 0) == 77);
            });

            clientThread.Start();

            var rep = NN.Socket(Domain.SP, Protocol.REP);

            NN.Bind(rep, inprocAddress);
            NN.Recv(rep, out buffer2, SendRecvFlags.NONE);
            Debug.Assert(BitConverter.ToInt32(buffer2, 0) == 42);
            NN.Send(rep, BitConverter.GetBytes((int)77), SendRecvFlags.NONE);

            // TODO: Test connection of multiple REQ clients to a single REP server.
        }
예제 #2
0
 public Response(INanoConnection c)
 {
     byte[] buf;
     NN.SetSockOpt(c.Socket, SocketOption.RCVTIMEO, (int)c.ConnectionTimeout.TotalMilliseconds);
     if (NN.Recv(c.Socket, out buf, SendRecvFlags.NONE) < 0)
     {
         throw new NanoNetworkCommandException("Error receiving response");
     }
     MemoryStream = new MemoryStream(buf);
     BinaryReader = new BinaryReader(MemoryStream);
 }
예제 #3
0
            public static void Request()
            {
                var req = NN.Socket(Domain.SP, Protocol.REQ);

                NN.Connect(req, MessageQueueConstants.Address);

                Debug.WriteLine("Request: Sending request");
                NN.Send(req, Encoding.ASCII.GetBytes(MessageQueueConstants.RequestPayload), SendRecvFlags.NONE);

                Debug.WriteLine("Request: Receiving reply");
                byte[] replyPayload;
                NN.Recv(req, out replyPayload, SendRecvFlags.NONE);
                Assert.IsTrue(BitConverter.ToInt32(replyPayload, 0) == MessageQueueConstants.ReplyPayload);
            }
예제 #4
0
        public static void Execute()
        {
            Console.WriteLine("Executing Listener test");

            const string inprocAddress = "tcp://127.0.0.1:6522";
            const string unusedAddress = "tcp://127.0.0.1:6521";

            byte[] buffer1;
            byte[] buffer2;

            var clientThread = new Thread(
                () =>
            {
                var req1 = NN.Socket(Domain.SP, Protocol.REQ);
                NN.Connect(req1, unusedAddress);
                var req = NN.Socket(Domain.SP, Protocol.REQ);
                NN.Connect(req, inprocAddress);
                Thread.Sleep(TimeSpan.FromSeconds(3));
                NN.Send(req, BitConverter.GetBytes((int)42), SendRecvFlags.NONE);
                NN.Recv(req, out buffer1, SendRecvFlags.NONE);
                Debug.Assert(BitConverter.ToInt32(buffer1, 0) == 77);
                Console.WriteLine("Response: " + BitConverter.ToInt32(buffer1, 0));
            });

            clientThread.Start();

            var unused = NN.Socket(Domain.SP, Protocol.REP);

            NN.Bind(unused, unusedAddress);
            var rep = NN.Socket(Domain.SP, Protocol.REP);

            NN.Bind(rep, inprocAddress);

            var listener = new NanomsgListener();

            listener.AddSocket(unused);
            listener.AddSocket(rep);
            listener.ReceivedMessage += delegate(int s)
            {
                NN.Recv(s, out buffer2, SendRecvFlags.NONE);
                Console.WriteLine("Message: " + BitConverter.ToInt32(buffer2, 0));
                NN.Send(s, BitConverter.GetBytes((int)77), SendRecvFlags.NONE);
            };

            while (true)
            {
                listener.Listen(TimeSpan.FromMinutes(30));
            }
        }
예제 #5
0
        public override void Receive(out byte[] envelope, out byte[] data)
        {
            byte[] toRcv;
            NN.Recv(this.innerSocket.SocketID, out toRcv, SendRecvFlags.NONE);

            int envEnd    = this.IndexOf(toRcv, Global.NANOMSG_SPLITTER);
            int dataStart = envEnd + Global.NANOMSG_SPLITTER.Length;

            envelope = new byte[envEnd];
            data     = new byte[toRcv.Length - dataStart];
            Array.Copy(toRcv, 0, envelope, 0, envEnd);
            Array.Copy(toRcv, dataStart, data, 0, toRcv.Length - dataStart);
            //var contains = !Global.NANOMSG_SPLITTER.Except(toRcv).Any();

            //envelope = this.innerSocket.Receive();
            //data = this.innerSocket.Receive();
        }
예제 #6
0
            public static void Response(CancellationToken cancelToken)
            {
                var rep = NN.Socket(Domain.SP, Protocol.REP);

                NN.Bind(rep, MessageQueueConstants.Address);

                while (!cancelToken.IsCancellationRequested)
                {
                    byte[] payloadBytes;
                    NN.Recv(rep, out payloadBytes, SendRecvFlags.NONE);
                    Debug.WriteLine("Response: Received request");

                    var payload = Encoding.ASCII.GetString(payloadBytes);
                    Assert.IsTrue(payload.Equals(MessageQueueConstants.RequestPayload));

                    Debug.WriteLine("Response: Sending reply");
                    NN.Send(rep, BitConverter.GetBytes(MessageQueueConstants.ReplyPayload), SendRecvFlags.NONE);
                }
            }
예제 #7
0
        public static void Execute()
        {
            const string inprocAddress = "inproc://getsetoption_test";

            int v;

            byte[] bs;

            var s  = NN.Socket(Domain.SP, Protocol.REP);
            var rc = NN.SetSockOpt(s, SocketOption.RCVTIMEO, 5000);

            Debug.Assert(rc >= 0);
            rc = NN.GetSockOpt(s, SocketOption.RCVTIMEO, out v);
            Debug.Assert(rc >= 0);

            NN.Bind(s, inprocAddress);
            NN.Recv(s, out bs, SendRecvFlags.NONE);

            // setting the rcvtimeo works as expected.
        }
예제 #8
0
        public static int SetupServerSocketsFindPort(
            int portRangeStart, int portRangeEnd, byte componentId,
            Dictionary <byte, NetworkHandlerDelegate> handlers,
            object debug_commandIdType,
            TimeSpan commsTimeout,
            LogMessageDelegate logMessage)
        {
            _listener.ReceivedMessage += delegate(int s)
            {
                byte component = 255;
                byte command   = 255;

                try
                {
                    byte[] data;

                    NN.SetSockOpt(s, SocketOption.RCVTIMEO, (int)commsTimeout.TotalMilliseconds);
                    NN.Recv(s, out data, SendRecvFlags.NONE);

                    if (data == null || data.Length == 0)
                    {
                        throw new Exception("received empty command.");
                    }

                    using (var msi = new MemoryStream(data))
                        using (var br = new BinaryReader(msi))
                            using (var mso = new MemoryStream())
                                using (var bw = new BinaryWriter(mso))
                                {
                                    component = br.ReadByte();
                                    if (component != componentId)
                                    {
                                        throw new Exception("Component with id " + componentId +
                                                            " errantly received a command for component " + component);
                                    }
                                    command = br.ReadByte();
                                    if (debug_commandIdType != null)
                                    {
                                        logMessage(TraceLevel.Verbose, ">> " + Enum.GetName((Type)debug_commandIdType, command));
                                    }
                                    handlers[command](br, bw);
                                    NN.SetSockOpt(s, SocketOption.SNDTIMEO, (int)commsTimeout.TotalMilliseconds);
                                    var rc = NN.Send(s, mso.ToArray(), SendRecvFlags.NONE);

                                    if (rc < 0)
                                    {
                                        if (debug_commandIdType != null)
                                        {
                                            logMessage(TraceLevel.Verbose, "!< ERROR sending reply: " + Enum.GetName((Type)debug_commandIdType, command));
                                        }
                                        else
                                        {
                                            logMessage(TraceLevel.Verbose, "!< ERROR sending reply, ignoring.");
                                        }
                                    }
                                    else
                                    {
                                        if (debug_commandIdType != null)
                                        {
                                            logMessage(TraceLevel.Verbose, " < " + Enum.GetName((Type)debug_commandIdType, command));
                                        }
                                    }
                                }
                }
                catch (Exception e)
                {
                    logMessage(TraceLevel.Error, "Error handling command [component id: " + component + "] [command id: " + command + "]: " + Utils.UnrolledExceptionMessage(e));
                }
            };


            var socket = NN.Socket(Domain.SP, Protocol.REP);

            NN.SetSockOpt(socket, SocketOption.SNDBUF, 5000000);
            NN.SetSockOpt(socket, SocketOption.RCVBUF, 5000000);

            for (int portTry = portRangeStart; portTry <= portRangeEnd; ++portTry)
            {
                if (PortInUse(portTry))
                {
                    continue;
                }

                try
                {
                    var rc = NN.Bind(socket, "tcp://*:" + portTry);
                    if (rc < 0)
                    {
                        continue;
                    }
                }
                catch
                {
                    Thread.ResetAbort();
                    continue;
                }

                _socketPorts.Add(socket, portTry);
                _listener.AddSocket(socket);

                return(portTry);
            }

            throw new Exception("no free ports available in range " + portRangeStart + " -> " + portRangeEnd);
        }
예제 #9
0
        public static void SetupServerSockets(
            Dictionary <int, Dictionary <byte, NetworkHandlerDelegate> > handlers,
            Dictionary <int, byte> interfaceIds,
            Dictionary <int, object> debug_commandIdTypes,
            TimeSpan commsTimeout,
            LogMessageDelegate logMessage)
        {
            var ports = handlers.Keys.ToList();

            // todo: assert all three dictionarys specify same port numbers.

            _listener.ReceivedMessage += delegate(int s)
            {
                byte interfaceId = 255;
                byte command     = 255;
                int  port        = -1;

                try
                {
                    byte[] data;

                    NN.SetSockOpt(s, SocketOption.RCVTIMEO, (int)commsTimeout.TotalMilliseconds);
                    NN.Recv(s, out data, SendRecvFlags.NONE);

                    if (data == null || data.Length == 0)
                    {
                        throw new Exception("data was ready to be received but wasn't. I don't expect this should happen.");
                    }

                    using (var msi = new MemoryStream(data))
                        using (var br = new BinaryReader(msi))
                            using (var mso = new MemoryStream())
                                using (var bw = new BinaryWriter(mso))
                                {
                                    interfaceId = br.ReadByte();
                                    command     = br.ReadByte();
                                    port        = _socketPorts[s];
                                    if (interfaceIds[port] != interfaceId)
                                    {
                                        throw new Exception("Component with id " + interfaceIds[port] +
                                                            " errantly received a command for component " + interfaceId);
                                    }
                                    if (debug_commandIdTypes[port] != null)
                                    {
                                        logMessage(TraceLevel.Verbose, ">> " + Enum.GetName((Type)debug_commandIdTypes[port], command));
                                    }
                                    handlers[port][command](br, bw);

                                    NN.SetSockOpt(s, SocketOption.SNDTIMEO, (int)commsTimeout.TotalMilliseconds);
                                    var rc = NN.Send(s, mso.ToArray(), SendRecvFlags.NONE);

                                    if (rc < 0)
                                    {
                                        if (debug_commandIdTypes[port] != null)
                                        {
                                            logMessage(TraceLevel.Verbose, "!< ERROR sending reply: " +
                                                       Enum.GetName((Type)debug_commandIdTypes[port], command));
                                        }
                                        else
                                        {
                                            logMessage(TraceLevel.Verbose, "!< ERROR sending reply, ignoring.");
                                        }
                                    }
                                    else
                                    {
                                        if (debug_commandIdTypes[port] != null)
                                        {
                                            logMessage(TraceLevel.Verbose, " < " + Enum.GetName((Type)debug_commandIdTypes[port], command));
                                        }
                                    }
                                }
                }
                catch (Exception e)
                {
                    logMessage(TraceLevel.Error, "Error handling command [component id: " + interfaceId + "] [command id: " + command + "] [port " + port + "]: " + Utils.UnrolledExceptionMessage(e));
                }
            };

            // Create the server socket on which to listen, bind them, and start listening.
            for (int i = 0; i < ports.Count; ++i)
            {
                var socket = NN.Socket(Domain.SP, Protocol.REP);
                NN.SetSockOpt(socket, SocketOption.SNDBUF, 5000000);
                NN.SetSockOpt(socket, SocketOption.RCVBUF, 5000000);

                NN.Bind(socket, "tcp://*:" + ports[i]);

                _listener.AddSocket(socket);
                _socketPorts.Add(socket, ports[i]);
            }
        }