コード例 #1
0
ファイル: Binder.cs プロジェクト: slawer/service
        private string resultData = string.Empty; // результирующие данные при операции чтения

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Инициализирует новый экземпляр класса
        /// </summary>
        public Binder(IApplication app)
        {
            application = app;
            proto = application.GetProtocol(ProtocolVersion.x100);

            options = new IoOptions();
        }
コード例 #2
0
ファイル: TcpHost.cs プロジェクト: anjing/TCPChannel
        /// <summary>
        /// Start listener port and process messages received
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool Start(int port)
        {
            tcpProtocol = new TcpProcotol();
            tcpProtocol.RegisterHandler(this);
            this.port = port;
            try
            {
                if (!isRunning)
                {
                    Console.WriteLine("Start listen port:{0}", port);
                    isRunning = true;
                    ThreadStart ts = new ThreadStart(ListenForData);
                    dataListener = new Thread(ts);
                    dataListener.Start();

                    // Start message processing thread
                    ts = new ThreadStart(ProcessMessageList);
                    messageProcessor = new Thread(ts);
                    messageProcessor.Start();
                }
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Can not start event controller, error:{0}", e.Message);
                return false;
            }
        }
コード例 #3
0
        private IConnection OpenConnection(RabbitMQUri uri, IProtocol protocol)
        {
            int port = uri.Port.HasValue ? uri.Port.Value : protocol.DefaultPort;

            ConnectionFactory connFactory = new ConnectionFactory
                {
                    AutomaticRecoveryEnabled = true,
                    HostName = uri.Host,
                    Port = port,
                    Protocol = protocol
                };

            if (uri.Username != null)
            {
                connFactory.UserName = uri.Username;
            }
            if (uri.Password != null)
            {
                connFactory.Password = uri.Password;
            }
            if (uri.VirtualHost != null)
            {
                connFactory.VirtualHost = uri.VirtualHost;
            }

            return connFactory.CreateConnection();
        }
コード例 #4
0
 ///<summary>Uses AmqpTcpEndpoint.Parse and .ParseMultiple to
 ///convert the strings, and then passes them to the other
 ///overload of the constructor.</summary>
 public RedirectException(IProtocol protocol,
                          string host,
                          string knownHosts)
     : this(ParseHost(protocol, host),
            AmqpTcpEndpoint.ParseMultiple(protocol, knownHosts))
 {
 }
コード例 #5
0
ファイル: Peer.cs プロジェクト: brainster-one/khrussk
 /// <summary>Initializes a new instance of the Peer class using the specified socket and protocol.</summary>
 /// <param name="socket">Socket.</param>
 /// <param name="protocol">Protocol.</param>
 internal Peer(Socket socket, IProtocol protocol)
 {
     _socket = socket;
     _protocol = protocol;
     _socket.ConnectionStateChanged += OnSocketConnectionStateChanged;
     _socket.DataReceived += OnSocketDataReceived;
 }
コード例 #6
0
ファイル: SerialPortServer.cs プロジェクト: gbcwbz/ModbusTool
 public SerialPortServer(
     SerialPort port,
     IProtocol protocol)
 {
     Port = port;
     Protocol = protocol;
 }
コード例 #7
0
ファイル: AbstractECU.cs プロジェクト: Tomic-Tech/JM.Core
 public AbstractECU(ICommbox commbox)
 {
     this.commbox = commbox;
     this.protocol = null;
     this.pack = new NoPack();
     stopReadDataStream = false;
 }
コード例 #8
0
ファイル: Form1.cs プロジェクト: slawer/service
        /// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="application">Интерфейс связи с платформой</param>
        public Form1(IApplication application)
        {
            app = application;
            protocol = app.GetProtocol(ProtocolVersion.x100);
            try
            {
                par = LoadConfiguration(Application.StartupPath + ParametrConstants.ConfigName);
            }
            catch
            {
                par = new SetTimeParameters();
            }

            InitializeComponent();

            this.boxArray[0] = this.button1;
            this.boxArray[1] = this.button2;
            this.boxArray[2] = this.button5;
            this.boxArray[3] = this.button6;
            this.boxArray[4] = this.button7;
            this.boxArray[5] = this.button8;
            this.boxArray[6] = this.button9;

            SetImageForm();
        }
コード例 #9
0
 public void can_evaluate_6()
 {
     auftrag = new Auftrag(new Systemschein( new Systemfeld( 1, 2, 3, 4, 5, 6, 7) { SID = 7 }));
     protocol = auftrag.Tipps[0].evaluate(ausspielung);
     Assert.That(protocol.Hits[2], Is.EqualTo(1));
     Assert.That(protocol.Hits[4], Is.EqualTo(6));
 }
コード例 #10
0
 public void can_evaluate_4()
 {
     auftrag = new Auftrag(new Systemschein( new Systemfeld( 1, 2, 3, 4, 7, 8, 9) { SID = 7 }));
     protocol = auftrag.Tipps[0].evaluate(ausspielung);
     Assert.That(protocol.Hits[6], Is.EqualTo(3));
     Assert.That(protocol.Hits[8], Is.EqualTo(4));
 }
コード例 #11
0
ファイル: MainForm.cs プロジェクト: slawer/service
        /// <summary>
        /// Конструктор класса
        /// </summary>
        /// <param name="app">Ссылка на платформу</param>
        /// <param name="pBios">Ссылка на подсистему ввода/вывода платформы</param>
        public MainForm(IApplication app, IEpromIO pBios, IProtocol protocol)
        {
            InitializeComponent();
            textInserter = new TextInsert(InsertToText);

            oldValue = new object();
            newValue = new object();

            oldValue = "0";
            newValue = "0";

            bios = new BIOS(app, pBios);
            proto = protocol;

            currentState = new ObjectCurrentState();

            for (int i = 0; i < 11; i++)
            {
                DataGridViewRow r = new DataGridViewRow();
                if ((i % 2) == 0) r.DefaultCellStyle.BackColor = Color.WhiteSmoke;
                dataGridViewCalibrationTable.Rows.Add(r);
            }

            syncker = new Sync();
            packetSyncMutex = new Mutex(false);

            gr = new GraphicCalibration(CreateGraphics(), new Rectangle(12, 38, 422, 267));
            gr.CalculateScale();
        }
コード例 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TcpServer"/> class.
        /// </summary>
        /// <remarks>If the port number is in range of the well-known ports [0 - 1024] the default port 80 is taken.</remarks>
        /// <param name="service">The TCP Service implementation which can handle the incoming requests.</param>
        /// <param name="portNumber">The port where this server should listen on incoming connections. Must be > 1023.</param>
        /// <exception cref="PlatformNotSupportedException">Is thrown when the underlying operating system does not support <see cref="HttpListener"/>s.</exception>
        /// <exception cref="ArgumentNullException">Is thrown when <paramref name="service"/> is a null reference.</exception>
        /// <exception cref="ArgumentException">Is thrown when <paramref name="portNumber"/> is bigger than 65535.</exception>
        public TcpServer(IProtocol service, int portNumber)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service", "The Service endpoint must be an instance.");
            }

            if (portNumber > TcpServer.BiggestPossiblePortNumber)
            {
                throw new ArgumentException("The port number must be smaller than " + (TcpServer.BiggestPossiblePortNumber + 1) + ".", "portNumber");
            }

            if (portNumber < TcpServer.SmallestPossiblePortNumber)
            {
                _logger.WarnFormat("Using default port number {0} to listen on TCP requests.", portNumber);
                this.ListeningPort = DefaultPortNumber;
            }

            var localAddress = IPAddress.Parse("127.0.0.1");
            _tcpListener = new TcpListener(localAddress, portNumber);
            _serviceEndpoint = service;
            _logger.DebugFormat(CultureInfo.CurrentCulture, "TCP Listener created on port: " + portNumber);

            this._signals[ExitThread] = this._stopThreadEvent;
            this._signals[LookForNextConnection] = this._listenForConnection;
        }
コード例 #13
0
 public void can_evaluate_4()
 {
     auftrag = new Auftrag(new Systemschein( new Systemfeld( 1, 2, 3, 4, 8, 9, 10, 11, 12, 13) { SID = 10 }));
     protocol = auftrag.Tipps[0].evaluate(ausspielung);
     Assert.That(protocol.Hits[6], Is.EqualTo(15));
     Assert.That(protocol.Hits[8], Is.EqualTo(80));
 }
コード例 #14
0
ファイル: TcpHost.cs プロジェクト: anjing/TCPChannel
 public void HandleEvent(IProtocol protocol, IEvent e)
 {
     EventId eid = (EventId)e.ID;
     switch (eid)
     {
         case EventId.Disconnect:
             Stop();
             break;
         case EventId.SendMessage:
             if (!protocol.isClosed())
             {
                 if (transport != null)
                 {
                     transport.Send(e.Data);
                 }
             }
             break;
         case EventId.Media:
             Console.WriteLine("media event received, id={0}", eid);
             break;
         case EventId.Content:
             break;
         case EventId.Stack:
             break;
         case EventId.Schedule:
             break;
     }
 }
コード例 #15
0
 /// <summary>
 /// Creates a RecieveThread to recieve messages on the specified protocol
 /// </summary>
 /// <param name="protocol">The protocol to recieve messages from</param>
 /// <param name="server">The server to recieve for</param>
 public RecieveThread(IProtocol protocol, INovaServer server)
 {
     protocols.Add(protocol);
     this.server = server;
     thread = new Thread(RecieveLoop);
     log = LogManager.GetLogger(typeof(RecieveThread));
 }
コード例 #16
0
ファイル: Peer.cs プロジェクト: brainster-one/khrussk
 /// <summary>Initializes a new instance of the Peer class using the specified protocol.</summary>
 /// <param name="protocol">Protocol.</param>
 public Peer(IProtocol protocol)
 {
     _protocol = protocol;
     _socket = new Socket();
     _socket.ConnectionStateChanged += OnSocketConnectionStateChanged;
     _socket.DataReceived += OnSocketDataReceived;
 }
コード例 #17
0
 ///<summary>Construct an AmqpTcpEndpoint with the given
 ///IProtocol, hostname, port number and ssl option. If the port 
 ///number is -1, the default port number for the IProtocol 
 ///will be used.</summary>
 public AmqpTcpEndpoint(IProtocol protocol, string hostName, int portOrMinusOne, SslOption ssl)
 {
     m_protocol = protocol;
     m_hostName = hostName;
     m_port = portOrMinusOne;
     m_ssl = ssl;
 }
コード例 #18
0
        private ConnectionFactory GetConnectionFactory(IProtocol protocol, RabbitMqAddress brokerAddress)
        {
            ConnectionFactory factory = null;
            var key = string.Format("{0}:{1}", protocol, brokerAddress);

            if(!connectionFactories.TryGetValue(key, out factory))
            {
                factory = new ConnectionFactory();
                factory.Endpoint = new AmqpTcpEndpoint(protocol, brokerAddress.Broker);

                if(!string.IsNullOrEmpty(brokerAddress.VirtualHost))
                    factory.VirtualHost = brokerAddress.VirtualHost;

                if(!string.IsNullOrEmpty(brokerAddress.Username))
                    factory.UserName = brokerAddress.Username;

                if(!string.IsNullOrEmpty(brokerAddress.Password))
                    factory.Password = brokerAddress.Password;

                factory = connectionFactories.GetOrAdd(key, factory);
                log.Debug("Opening new Connection Factory " + brokerAddress + " using " + protocol.ApiName);
            }

            return factory;
        }
コード例 #19
0
        private IConnection GetConnection(IProtocol protocol, RabbitMqAddress brokerAddress, ConnectionFactory factory)
        {
            IConnection connection = null;
            var key = string.Format("{0}:{1}", protocol, brokerAddress);

            if (!connections.TryGetValue(key, out connection))
            {
                var newConnection = factory.CreateConnection();
                connection = connections.GetOrAdd(key, newConnection);

                //if someone else beat us from another thread kill the connection just created
                if(newConnection.Equals(connection) == false)
                {
                    newConnection.Dispose();
                }
                else
                {
                    log.DebugFormat("Opening new Connection {0} on {1} using {2}",
                                    connection, brokerAddress, protocol.ApiName);
                }

            }

            return connection;
        }
コード例 #20
0
 public void can_evaluate_6_ZZ()
 {
     // ausspielung =: Superzahl == 0 !!!
     auftrag = new Auftrag(new Normalschein( new Normalfeld( 1, 2, 3, 4, 5, 6)) { Losnummer = "0000000" });
     protocol = auftrag.Tipps[0].evaluate(ausspielung);
     Assert.That(protocol.Hits[1], Is.EqualTo(1));
 }
コード例 #21
0
ファイル: StreamConnection.cs プロジェクト: krishnarajv/Code
 internal StreamConnection(IReactor dispatcher, IProtocol protocol, TcpClient tcpClient, int bufferSize)
     : base(dispatcher, protocol)
 {
     _tcpClient = tcpClient;
     _readBuffer = new Byte[bufferSize];
     _remoteEndPoint = _tcpClient.Client.RemoteEndPoint as IPEndPoint;
 }
コード例 #22
0
ファイル: ServerCommData.cs プロジェクト: gbcwbz/ModbusTool
 public ServerCommData(
     IProtocol protocol, 
     ByteArrayReader incomingData = null)
     : base(protocol)
 {
     IncomingData = incomingData;
 }
コード例 #23
0
ファイル: ValueProtocol.cs プロジェクト: WangxuHub/WebSocket
        public Byte[] GetResponse(String request)
        {
            String version = getVersion(request);
            if (version == "13")
                protocol = new ProtocolDraft10();

            return protocol.ProduceResponse(request);
        }
コード例 #24
0
        public MetaverseSession(IProtocol protocol)
        {
            m_protocol = protocol;

            m_protocol.OnConnected += OnConnected;
            m_protocol.OnLandPatch += OnLandPatch;
            m_protocol.OnChat += ModelChat;
        }
コード例 #25
0
 public void can_evaluate_5()
 {
     auftrag = new Auftrag(new Systemschein( new Systemfeld( 1, 2, 3, 4, 5, 9, 10, 11, 12) { SID = 9 }));
     protocol = auftrag.Tipps[0].evaluate(ausspielung);
     Assert.That(protocol.Hits[4], Is.EqualTo(4));
     Assert.That(protocol.Hits[6], Is.EqualTo(30));
     Assert.That(protocol.Hits[8], Is.EqualTo(40));
 }
コード例 #26
0
ファイル: Target.cs プロジェクト: Joxx0r/ATF
        /// <summary>
        /// Constructor</summary>
        /// <param name="target">The ITarget whose information will be displayed</param>
        /// <param name="protocol">The target's protocol</param>
        public TargetViewModel(ITarget target, IProtocol protocol)
        {
            Requires.NotNull(target, "target");
            Requires.NotNull(protocol, "protocol");

            Target = target;
            m_protocol = protocol;
        }
コード例 #27
0
ファイル: SocketExtensions.cs プロジェクト: gbcwbz/ModbusTool
 /// <summary>
 /// Return a concrete implementation of a UDP listener
 /// </summary>
 /// <param name="port"></param>
 /// <param name="protocol"></param>
 /// <returns></returns>
 public static ICommServer GetUdpListener(
     this Socket port,
     IProtocol protocol)
 {
     return new UdpServer(
         port,
         protocol);
 }
コード例 #28
0
 public void can_evaluate_3_ZZ()
 {
     // ausspielung =: Zusatzzahl == 49 !!!
     auftrag = new Auftrag(new Systemschein( new Systemfeld( 1, 2, 3, 7, 8, 9, 10, 11, 12, 49) { SID = 10 }));
     protocol = auftrag.Tipps[0].evaluate(ausspielung);
     Assert.That(protocol.Hits[7], Is.EqualTo(15));
     Assert.That(protocol.Hits[8], Is.EqualTo(20));
 }
コード例 #29
0
 public IndicatorReaderWorker(IProtocol protocol, BlockingCollection<float[]> output, TimeSpan timeout)
 {
     _protocol = protocol;
     _output = output;
     _timeout = timeout;
     _timer = new Timer {AutoReset = true, Enabled = false, Interval = timeout.TotalMilliseconds};
     _timer.Elapsed += TimerOnElapsed;
 }
コード例 #30
0
ファイル: Engine.cs プロジェクト: BiZonZon/a-team-connect4
 /// <summary>
 /// 
 /// </summary>
 /// <param name="board"></param>
 /// <param name="protocol">Protocol will be used to write output of bestline</param>
 public Engine(Board board, IProtocol protocol)
 {
     Exit = false;
     Board = board;
     Protocol = protocol;
     elapsedTime = new Stopwatch();
     historyMoves = new HistoryMoves();
     killerMoves = new KillerMoves();
 }
コード例 #31
0
ファイル: DeviceTests.cs プロジェクト: Navaladi2019/UnitTest
        public void Connect_FailedThrice_ThreeTries()
        {
            IProtocol provider = Substitute.For <IProtocol>();

            provider.Connect(Arg.Any <string>()).ReturnsForAnyArgs(false);

//            provider.Connect(Arg.Is("COM1")).Returns(true);
//            provider.Connect(Arg.Is<string>(x=>x.StartsWith("COM"))).Returns(true);

            var sut = new Device(provider);

            sut.Connect(string.Empty);

            provider.Received(3).Connect(Arg.Any <string>());
        }
コード例 #32
0
        public static IProtocol CreateProtocol(ISerializer serializer)
        {
            IProtocol protocol = NSubstitute.Substitute.For <IProtocol>();

            System.Collections.Generic.Dictionary <System.Type, System.Type> types = new System.Collections.Generic.Dictionary <System.Type, System.Type>();
            types.Add(typeof(IGpiA), typeof(GhostIGpiA));
            InterfaceProvider interfaceProvider = new InterfaceProvider(types);

            protocol.GetInterfaceProvider().Returns(interfaceProvider);
            protocol.GetSerialize().Returns(serializer);
            System.Func <IProvider> gpiaProviderProvider = () => new TProvider <IGpiA>();
            System.Tuple <System.Type, System.Func <IProvider> >[] typeProviderProvider = new System.Tuple <System.Type, System.Func <IProvider> >[] { new System.Tuple <System.Type, System.Func <IProvider> >(typeof(IGpiA), gpiaProviderProvider) };
            protocol.GetMemberMap().Returns(new MemberMap(new System.Reflection.MethodInfo[0], new System.Reflection.EventInfo[0], new System.Reflection.PropertyInfo[0], typeProviderProvider));
            return(protocol);
        }
コード例 #33
0
        public OpenMediaNotReadyAction(IProtocol protocol) :
            base(protocol)
        {
            base.Request = RequestNotReadyForMedia.Create("chat", null);

            OrPredicate <IMessage> filter = new OrPredicate <IMessage>(
                new MessageIdFilter(EventAck.MessageId),
                new MessageIdFilter(EventAgentNotAvailable.MessageId));

            filter.AddPredicate(new AgentStatusFilter("chat", 0));

            base.SuccessFilter = filter;

            base.FailureFilter = new MessageIdFilter(EventError.MessageId);
        }
コード例 #34
0
ファイル: ProtocolTester.cs プロジェクト: dndoanh/navtrack
        public ProtocolTester(IProtocol protocol, ICustomMessageHandler customMessageHandler)
        {
            cancellationTokenSource = new CancellationTokenSource();
            TotalParsedLocations    = new List <Location>();

            Client = new Client
            {
                Protocol         = protocol,
                DeviceConnection = new DeviceConnectionEntity()
            };

            SetupLocationService();
            SetupStreamHandler(customMessageHandler);
            SetupNetworkStreamMock();
        }
コード例 #35
0
        public void Handling(IProtocol protocol, Form form)
        {
            var ptc = protocol as AddUserInGroupResponseProtocol;

            if (!(form is FormMain))
            {
                return;
            }
            var f = form as FormMain;

            f.Invoke(new MethodInvoker(delegate()
            {
                f.SendRequestGetUserInGroup(ptc.GroupId);
            }));
        }
コード例 #36
0
        public string Handling(IProtocol protocol, IChatClient client)
        {
            var    ptc       = protocol as GetGroupChatRequestProtocol;
            string toView    = "[" + DateTime.Now + "] [" + client.GetEndPoint() + "] [user:"******"] get groups chat";
            var    listGroup = GetListGroup(ptc.Email);

            if (listGroup.Count == 0)
            {
                toView += "\n list group empty";
                return(toView);
            }
            client.ResponseGetGroups(listGroup);
            toView += "\n get list group OK!";
            return(toView);
        }
コード例 #37
0
        public SoulProvider(IRequestQueue peer, IResponseQueue queue, IProtocol protocol)
        {
            _WaitValues  = new Dictionary <long, IValue>();
            _Souls       = new System.Collections.Concurrent.ConcurrentDictionary <long, SoulProxy>();
            _EventFilter = new Queue <byte[]>();
            _IdLandlord  = new IdLandlord();
            _Queue       = queue;
            _Protocol    = protocol;

            _EventProvider = protocol.GetEventProvider();

            _Serializer              = protocol.GetSerialize();
            _Peer                    = peer;
            _Peer.InvokeMethodEvent += _InvokeMethod;
        }
コード例 #38
0
 public void Connect()
 {
     try
     {
         IProtocol protocol = protocolManagementService[ISERVER_IDENTIFIER];
         if (protocol.State == ChannelState.Closed)
         {
             protocol.BeginOpen();
         }
     }
     catch (Exception e)
     {
         LogException(e);
     }
 }
コード例 #39
0
ファイル: AmqpTcpEndpoint.cs プロジェクト: pmq20/mono_forked
        ///<summary>Splits the passed-in string on ",", and passes the
        ///substrings to AmqpTcpEndpoint.Parse()</summary>
        ///<remarks>
        /// Accepts a string of the form "hostname:port,
        /// hostname:port, ...", where the ":port" pieces are
        /// optional, and returns a corresponding array of
        /// AmqpTcpEndpoints.
        ///</remarks>
        public static AmqpTcpEndpoint[] ParseMultiple(IProtocol protocol, string addresses)
        {
            string[]  partsArr = addresses.Split(new char[] { ',' });
            ArrayList results  = new ArrayList();

            foreach (string partRaw in partsArr)
            {
                string part = partRaw.Trim();
                if (part.Length > 0)
                {
                    results.Add(Parse(protocol, part));
                }
            }
            return((AmqpTcpEndpoint[])results.ToArray(typeof(AmqpTcpEndpoint)));
        }
コード例 #40
0
        public void OnConnectButton()
        {
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            try
            {
                MessagePack.Resolvers.StaticCompositeResolver.Instance.Register(
                    MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance,
                    MessagePack.Unity.UnityResolver.Instance,
                    //MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance,
                    //MessagePack.Resolvers.StandardResolver.Instance,
                    MessagePack.Resolvers.ContractlessStandardResolver.Instance
                    );

                var options = MessagePack.MessagePackSerializerOptions.Standard.WithResolver(MessagePack.Resolvers.StaticCompositeResolver.Instance);
                MessagePack.MessagePackSerializer.DefaultOptions = options;
            }
            catch
            { }
#endif

            IProtocol protocol = null;
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            protocol = new MessagePackCSharpProtocol();
#elif BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
            protocol = new MessagePackProtocol();
#else
            protocol = new JsonProtocol(new LitJsonEncoder());
#endif

            // Crete the HubConnection
            hub = new HubConnection(new Uri(this.sampleSelector.BaseURL + this._path), protocol);

            // Subscribe to hub events
            hub.OnConnected += Hub_OnConnected;
            hub.OnError     += Hub_OnError;
            hub.OnClosed    += Hub_OnClosed;

            hub.OnRedirected += Hub_Redirected;

            hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));

            // And finally start to connect to the server
            hub.StartConnect();

            AddText("StartConnect called");

            SetButtons(false, false);
        }
コード例 #41
0
ファイル: Client.cs プロジェクト: forki/Sharp9P
 public Client(IProtocol protocol)
 {
     _msize    = Constants.DefaultMsize;
     _version  = Constants.DefaultVersion;
     _protocol = protocol;
     _tagQueue = new Queue();
     for (ushort i = 1; i < 65535; i++)
     {
         _tagQueue.Enqueue(i);
     }
     _fidQueue = new Queue();
     for (uint i = 2; i < 100; i++)
     {
         _fidQueue.Enqueue(i);
     }
 }
コード例 #42
0
 public void Disconnect()
 {
     try
     {
         IProtocol protocol = protocolManagementService[ISERVER_IDENTIFIER];
         if (protocol.State == ChannelState.Opened)
         {
             protocol.BeginClose();
         }
         LogMessage("断开成功");
     }
     catch (Exception e)
     {
         LogException(e);
     }
 }
コード例 #43
0
        private void ConnectIfNeeded()
        {
            var factory = ProtocolFactory;

            Precondition.PropertyNotNull(factory, nameof(ProtocolFactory));

            lock (lockObj)
            {
                if (protocol == null)
                {
                    var client = new TcpClient(hostname, port);
                    var stream = client.GetStream();
                    protocol = factory(stream);
                }
            }
        }
コード例 #44
0
        /// <summary>
        ///     Sets the protocol from a string.
        ///     Uses <see cref = "Protocols.Lookup" /> internally. It is
        ///		safe to pass both null and invalid protocols to this method (but
        ///		don't expect those invalid protocols to be used ;))
        /// </summary>
        /// <param name = "protocol"></param>
        public void SetProtocol(string protocol)
        {
            try
            {
                var safeLookup = SafeLookup(protocol);

                if (safeLookup != null)
                {
                    Protocol = safeLookup;
                }
            }
            catch (ConfigurationException e)
            {
                ErrorHandler.Error(string.Format("could not find protocol named '{0}'", protocol), e);
            }
        }
コード例 #45
0
 /// <summary>
 /// 消息协议
 /// </summary>
 /// <param name="arrays"></param>
 public MessageProtocol(string[] arrays)
 {
     this.success      = true;
     this.stationId    = arrays[0];
     this.serialNumber = arrays[1];
     this.messageId    = arrays[2];
     this.subMessageId = arrays[3];
     this.timeSpan     = arrays[4];
     this.validCode    = arrays[arrays.Length - 1];
     this.success      = true;
     if (this.subMessageId != RecSubMessageId)
     {
         //消息分发
         this.protocol = ProtocolHandler.GetProtocol(this.messageId, arrays);
     }
 }
コード例 #46
0
        public static ICommand CreateCommand(IProtocol protocol)
        {
            ICommand command = null;

            if (protocol is ExploreProtocol)
            {
                command = CreateCommand((ExploreProtocol)protocol);
            }

            if (command == null)
            {
                DebugUtility.LogError(LoggerTags.Project, "Failed to create command, Unknown protocol : {0}", protocol.ToString());
            }

            return(command);
        }
        public void Handling(IProtocol protocol, Form form)
        {
            var ptc = protocol as GetListFriendsResponseProtocol;

            if (!(form is FormMain))
            {
                return;
            }
            var f = form as FormMain;

            Instance.ListFriends = ptc.ListAccount;
            f.Invoke(new MethodInvoker(delegate()
            {
                f.LoadFriendList(Instance.ListFriends);
            }));
        }
コード例 #48
0
ファイル: Protocols.cs プロジェクト: claribou/Marvin
 ///<summary>Retrieve a protocol version by name (of one of the
 ///static properties on this class)</summary>
 ///<remarks>
 ///<para>
 /// If the argument is null, Protocols.DefaultProtocol is
 /// used. If the protocol variant named is not found,
 /// ConfigurationException is thrown.
 ///</para>
 ///<para>
 /// In many cases, FromEnvironment() will be a more
 /// appropriate method for applications to call; this method
 /// is provided for cases where the caller wishes to know the
 /// answer to the question "does a suitable IProtocol property
 /// with this name exist, and if so, what is its value?", with
 /// the additional guarantee that if a suitable property does
 /// not exist, a ConfigurationException will be thrown.
 ///</para>
 ///</remarks>
 ///<exception cref="ConfigurationException"/>
 public static IProtocol SafeLookup(string name)
 {
     if (name != null)
     {
         IProtocol p = Lookup(name);
         if (p != null)
         {
             return(p);
         }
         else
         {
             throw new ConfigurationException("Unsupported protocol variant name: " + name);
         }
     }
     return(DefaultProtocol);
 }
コード例 #49
0
        public void TestMessagingProtocol()
        {
            IChannel        channel0 = connection.GetChannel(0);
            IMessageFactory factory  = channel0.MessageFactory;

            IProtocol protocol = factory.Protocol;

            Assert.IsNotNull(protocol);
            Assert.IsInstanceOf(typeof(Initiator.MessagingProtocol), protocol);
            Assert.AreEqual(protocol.CurrentVersion, 3);
            Assert.AreEqual(protocol.SupportedVersion, 2);
            Assert.AreEqual(protocol.Name, Initiator.MessagingProtocol.PROTOCOL_NAME);
            IMessageFactory factory2 = protocol.GetMessageFactory(3);

            Assert.AreEqual(factory, factory2);
        }
コード例 #50
0
        public User(IStreamable client, IProtocol protocol)
        {
            Stream     = client;
            _Updater   = new ThreadUpdater(_Update);
            _Serialize = protocol.GetSerialize();

            _EnableLock = new object();

            _Peer         = client;
            _Protocol     = protocol;
            _SoulProvider = new SoulProvider(this, this, protocol);
            _Responses    = new System.Collections.Concurrent.ConcurrentQueue <ResponsePackage>();
            _Requests     = new System.Collections.Concurrent.ConcurrentQueue <RequestPackage>();
            _Reader       = new PackageReader <RequestPackage>(protocol.GetSerialize());
            _Writer       = new PackageWriter <ResponsePackage>(protocol.GetSerialize());
        }
コード例 #51
0
        /// <summary>
        /// 设定配置
        /// </summary>
        /// <param name="config"></param>
        public void SetConfig(Hashtable config)
        {
            if (packer == null && config.ContainsKey("packing"))
            {
                packer = App.Make(config["packing"].ToString()) as IPacking;
            }

            if (render == null && config.ContainsKey("render"))
            {
                if (config["render"] is Array)
                {
                    List <IRender> renders = new List <IRender>();
                    foreach (object obj in config["render"] as Array)
                    {
                        renders.Add(App.Make(obj.ToString()) as IRender);
                    }
                    render = renders.ToArray();
                }
                else
                {
                    render = new IRender[] { App.Make(config["render"].ToString()) as IRender };
                }
            }

            if (protocol == null && config.ContainsKey("protocol"))
            {
                protocol = App.Make(config["protocol"].ToString()) as IProtocol;
            }

            if (config.ContainsKey("host"))
            {
                host = config["host"].ToString();
            }

            if (config.ContainsKey("port"))
            {
                port = Convert.ToInt32(config["port"].ToString());
            }

            if (config.ContainsKey("event.level"))
            {
                if (config["event.level"] is Hashtable)
                {
                    triggerLevel = config["event.level"] as Hashtable;
                }
            }
        }
コード例 #52
0
ファイル: Connection.cs プロジェクト: jijiechen/PapercutCore
        public Connection(int id, Socket client, IProtocol protocol, ILogger logger)
        {
            // Initialize members
            Id       = id;
            Client   = client;
            Protocol = protocol;
            Logger   = logger;

            Logger.ForContext("ConnectionId", id);

            Connected    = true;
            LastActivity = DateTime.Now;

            BeginReceive();

            Protocol.Begin(this);
        }
コード例 #53
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SocketConnection_v772"/> class.
        /// </summary>
        /// <param name="logger">A reference to the logger in use.</param>
        /// <param name="socket">The socket that this connection is for.</param>
        /// <param name="protocol">The protocol in use by this connection.</param>
        public SocketConnection_v772(ILogger logger, Socket socket, IProtocol protocol)
        {
            logger.ThrowIfNull(nameof(logger));
            socket.ThrowIfNull(nameof(socket));
            protocol.ThrowIfNull(nameof(protocol));

            this.writeLock = new object();
            this.socket    = socket;
            this.stream    = new NetworkStream(this.socket);

            this.inboundMessage  = new NetworkMessage(isOutbound: false);
            this.xteaKey         = new uint[4];
            this.isAuthenticated = false;

            this.logger   = logger.ForContext <SocketConnection_v772>();
            this.protocol = protocol;
        }
コード例 #54
0
    public void SendPacket(IProtocol protocol)
    {
        using (var bw = new BinaryWriter(networkStream, Encoding.Default, true)) {
            protocol.Write(bw);
        }


        byte[] writeBuffer = new byte[protocol.GetPacketLength()];

        try {
            networkStream.Write(writeBuffer);
        } catch (Exception e) {
            Console.WriteLine(e);
            connectedServer.OnClientLeave(session_id);
            return;
        }
    }
コード例 #55
0
ファイル: ConnectionManager.cs プロジェクト: zzr1100/Papercut
        public Connection CreateConnection(Socket clientSocket, IProtocol protocol)
        {
            Interlocked.Increment(ref this._connectionID);
            Connection connection = this._connectionFactory(this._connectionID, clientSocket, protocol);

            connection.ConnectionClosed += this.ConnectionClosed;
            this._connections.TryAdd(connection.Id, connection);

            this.Logger.Debug(
                "New Connection {ConnectionId} from {RemoteEndPoint}",
                this._connectionID,
                clientSocket.RemoteEndPoint);

            this.InitCleanupObservables();

            return(connection);
        }
コード例 #56
0
        /// <summary>
        /// Constructs an OnFriendAddForm form.
        /// </summary>
        /// <param name="protocol">Associated protocol</param>
        /// <param name="friend">Person who's added you to their list</param>
        /// <param name="reason">[optional] Stranger's message</param>
        /// <param name="enableAddCheckbox">Whether to enable the add user checkbox</param>
        public OnFriendAddForm(IProtocol protocol, Friend friend, string reason, bool enableAddCheckbox)
        {
            this.protocol = protocol;
            this.friend   = friend;

            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            this.label.Text = friend.DisplayName + " (" + friend.Username + ") "
                              + "has added you to their contact list";
            this.textBox.Text            = reason;
            this.addUserCheckBox.Enabled = enableAddCheckbox;

            this.allowUserRadioButton.Checked = true;
        }
コード例 #57
0
        /// <summary>
        /// When the user enters a URI manually, we get the protocol to use for that URI (either by matching the prefix or using the default one) and then
        /// return the default connection data to use for that protocol.
        /// </summary>
        /// <param name="uri">URI that the user has entered.</param>
        /// <returns>The default connection data to use for the protocol corresponding to <paramref name="uri"/>.</returns>
        public static async Task <IConnection> GetConnection(string uri)
        {
            // Get the protocol for the URI
            Regex  uriCompontents = new Regex("^(?<prefix>(?<protocol>.+)://){0,1}(?<host>.+)$");
            Match  match          = uriCompontents.Match(uri);
            string protocolPrefix = match.Groups["protocol"].Success
                                                        ? match.Groups["protocol"].Value
                                                        : (await GetDefaultProtocol()).ProtocolPrefix;

            // Get the default connection data for the protocol
            IProtocol   protocol   = _protocols.First(pair => pair.Value.ProtocolPrefix.ToLower() == protocolPrefix.ToLower()).Value;
            IConnection connection = (IConnection)(await GetDefaults(protocol)).Clone();

            connection.Host = match.Groups["host"].Value;

            return(connection);
        }
コード例 #58
0
 public void Register(IProtocol protocol)
 {
     if (protocol == null)
     {
         return;
     }
     if (m_Protocols.ContainsKey(protocol.iCommand))           // 一个命令可以有多个回调方法
     {
         m_Protocols[protocol.iCommand].Add(protocol);
     }
     else           // 第一次添加
     {
         List <IProtocol> vars = new List <IProtocol>();
         vars.Add(protocol);
         m_Protocols.Add(protocol.iCommand, vars);
     }
 }
コード例 #59
0
        protected Service(Device aDevice, ServiceType aType, IProtocol aProtocol)
        {
            iDevice   = aDevice;
            iType     = aType;
            iProtocol = aProtocol;

            iActions = new List <Action>();

            try
            {
                iLocation = Device.FindServiceLocation(aType);
            }
            catch (DeviceException)
            {
                throw (new ServiceException(902, "Device failure"));
            }
        }
コード例 #60
0
        public OpenMediaLoginAction(IProtocol protocol, int tenantId, string placeId, string agentId) :
            base(protocol)
        {
            RequestAgentLogin reqAgentLogin = RequestAgentLogin.Create(tenantId, placeId, null);

            reqAgentLogin.AgentId   = agentId;
            reqAgentLogin.MediaList = new KeyValueCollection();;
            reqAgentLogin.MediaList.Add("chat", 1);

            base.Request = reqAgentLogin;

            base.SuccessFilter = new OrPredicate <IMessage>(
                new MessageIdFilter(EventAck.MessageId),
                new MessageIdFilter(EventAgentLogin.MessageId));

            base.FailureFilter = new MessageIdFilter(EventError.MessageId);
        }