Пример #1
0
        public NetworkConnection(IClient client, Notifier notifier, HandshakeFunc handshake,
                                 Message.GetEntryTypeFunc getEntryType)
        {
            Uid            = (uint)Interlocked.Increment(ref s_uid) - 1;
            m_client       = client;
            m_stream       = client.GetStream();
            m_notifier     = notifier;
            m_handshake    = handshake;
            m_getEntryType = getEntryType;

            Active     = false;
            ProtoRev   = 0x0300;
            m_state    = State.Created;
            LastUpdate = 0;

            IPEndPoint ipEp = m_client.RemoteEndPoint as IPEndPoint;

            if (ipEp != null)
            {
                PeerIP   = ipEp.Address.ToString();
                PeerPort = ipEp.Port;
            }
            else
            {
                PeerIP   = "";
                PeerPort = 0;
            }

            // turns of Nagle, as we bundle packets ourselves
            m_client.NoDelay = true;
        }
Пример #2
0
        public Task WaitForConnectionsAsync(Action <IModbusSession> onAcceptAction,
                                            HandshakeFunc <DefaultHandshake> handshakeFunc, bool supportForwardProtocol = false)
        {
            return(Task.Run(async() =>
            {
                var listner = _tcpListener;
                if (listner == null || onAcceptAction == null || handshakeFunc == null)
                {
                    return;
                }

                listner.Start();
                while (true)
                {
                    var tcpClient = await listner.AcceptTcpClientAsync();

                    if (supportForwardProtocol)
                    {
                        var modbusSession = ModbusSessionFactory.CreateFwdSession(tcpClient);
                        var handshake = handshakeFunc.Invoke(modbusSession);
                        if (handshake != null)
                        {
                            onAcceptAction.Invoke(modbusSession);
                        }
                        else
                        {
                            modbusSession.Dispose();
                        }
                    }
                    else
                    {
                        var modbusSession = ModbusSessionFactory.CreateTcpSession(tcpClient);
                        var handshake = handshakeFunc.Invoke(modbusSession);
                        if (handshake != null)
                        {
                            ((ModbusTcpSession)modbusSession).SetSlaveAddress(handshake.SlaveAddress);
                            onAcceptAction.Invoke(modbusSession);
                        }
                        else
                        {
                            modbusSession.Dispose();
                        }
                    }
                }
            }));
        }