Ejemplo n.º 1
0
        public void Should_Wait_When_ReadTimeout_Is_Zero()
        {
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(0);

            using (var simulacronCluster = SimulacronCluster.CreateNew(3))
            {
                const string cql = "SELECT key FROM system.local";
                simulacronCluster.Prime(new
                {
                    when = new { query = cql },
                    then = new
                    {
                        result            = "success",
                        delay_in_ms       = 30000,
                        rows              = new[] { new { key = "123" } },
                        column_types      = new { key = "ascii" },
                        ignore_on_prepare = false
                    }
                });

                using (var cluster = Cluster.Builder().AddContactPoint(simulacronCluster.InitialContactPoint).WithSocketOptions(socketOptions).Build())
                {
                    var session = cluster.Connect();
                    var query   = new SimpleStatement(cql);
                    var task    = session.ExecuteAsync(query);
                    Thread.Sleep(15000);
                    Assert.AreEqual(TaskStatus.WaitingForActivation, task.Status);
                    Thread.Sleep(15000);
                    TestHelper.RetryAssert(
                        () => { Assert.AreEqual(TaskStatus.RanToCompletion, task.Status, task.Exception?.ToString() ?? "no exception"); },
                        100,
                        50);
                }
            }
        }
Ejemplo n.º 2
0
        public void Should_Throw_NoHostAvailableException_When_All_Hosts_Down()
        {
            _testCluster = SimulacronCluster.CreateNew(2);
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(500);
            var builder       = Cluster.Builder().AddContactPoint(_testCluster.InitialContactPoint)
                                .WithSocketOptions(socketOptions);

            using (var cluster = builder.Build())
            {
                var session = cluster.Connect();
                //warmup
                TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
                _testCluster.Prime(new
                {
                    when = new { query = "SELECT key FROM system.local" },
                    then = new
                    {
                        result            = "success",
                        delay_in_ms       = 10000,
                        rows              = new[] { new { key = "123" } },
                        column_types      = new { key = "ascii" },
                        ignore_on_prepare = false
                    }
                });
                var ex = Assert.Throws <NoHostAvailableException>(() => session.Execute("SELECT key FROM system.local"));
                Assert.AreEqual(2, ex.Errors.Count);
                foreach (var innerException in ex.Errors.Values)
                {
                    Assert.IsInstanceOf <OperationTimedOutException>(innerException);
                }
            }
        }
Ejemplo n.º 3
0
        public void Should_Not_Leak_Connections_Test()
        {
            var testCluster   = TestClusterManager.CreateNew();
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(1).SetConnectTimeoutMillis(1);
            var builder       = Cluster.Builder()
                                .AddContactPoint(testCluster.InitialContactPoint)
                                .WithSocketOptions(socketOptions);

            testCluster.PauseNode(1);
            const int length = 1000;

            using (var cluster = builder.Build())
            {
                decimal initialLength = GC.GetTotalMemory(true);
                for (var i = 0; i < length; i++)
                {
                    var ex = Assert.Throws <NoHostAvailableException>(() => cluster.Connect());
                    Assert.AreEqual(1, ex.Errors.Count);
                }
                GC.Collect();
                Thread.Sleep(1000);
                testCluster.ResumeNode(1);
                Assert.Less(GC.GetTotalMemory(true) / initialLength, 1.3M,
                            "Should not exceed a 30% (1.3) more than was previously allocated");
            }
        }
Ejemplo n.º 4
0
        public BatchChannel(SocketOptions options, IChannel channel, BatchLetterBuilder batchBuilder)
        {
            _channel      = channel;
            _options      = options.Batch;
            _batchBuilder = batchBuilder;

            _channel.ChannelConnected     += abstractChannel => ChannelConnected(this);
            _channel.ChannelDisconnected  += ChannelOnDisconnected;
            _channel.ChannelQueueEmpty    += abstractChannel => {
                /* NOOP */
            };
            _channel.ChannelInitialized   += ChannelOnInitialized;
            _channel.ChannelConnecting    += abstractChannel => ChannelConnecting(this);
            _channel.ChannelDisconnecting += (abstractChannel, reason) => ChannelDisconnecting(this, reason);

            _channel.Received     += ChannelOnReceived;
            _channel.Sent         += ChannelOnSent;
            _channel.FailedToSend += ChannelOnFailedToSend;

            _slidingTimeoutTimer = new Timer(_options.Extend.TotalMilliseconds)
            {
                AutoReset = false
            };
            _slidingTimeoutTimer.Elapsed += SlidingTimeoutTimerOnElapsed;
        }
Ejemplo n.º 5
0
 public BinarySocketClient(IReactClientSocket webSocket, Uri uri, SocketOptions options)
 {
     _webSocket = webSocket;
     _uri       = uri;
     _options   = options;
     Initialize();
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Builds a request options object without any null settings.
        /// </summary>
        /// <param name="profile">Execution profile that was mapped into this instance. Can be null if it's the default profile.</param>
        /// <param name="defaultProfile">Default execution profile. Can be null.</param>
        /// <param name="policies">Must not be null and the inner policy settings must not be null either.</param>
        /// <param name="socketOptions">Must not be null.</param>
        /// <param name="queryOptions">Must not be null.</param>
        /// <param name="clientOptions">Must not be null.</param>
        public RequestOptions(
            IExecutionProfile profile,
            IExecutionProfile defaultProfile,
            Policies policies,
            SocketOptions socketOptions,
            QueryOptions queryOptions,
            ClientOptions clientOptions)
        {
            _profile        = profile;
            _defaultProfile = defaultProfile;
            _policies       = policies ?? throw new ArgumentNullException(nameof(policies));
            _socketOptions  = socketOptions ?? throw new ArgumentNullException(nameof(socketOptions));
            _queryOptions   = queryOptions ?? throw new ArgumentNullException(nameof(queryOptions));
            _clientOptions  = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));

            if (profile?.LoadBalancingPolicy == null && policies.LoadBalancingPolicy == null)
            {
                throw new ArgumentNullException(nameof(policies.LoadBalancingPolicy));
            }

            if (profile?.SpeculativeExecutionPolicy == null && policies.SpeculativeExecutionPolicy == null)
            {
                throw new ArgumentNullException(nameof(policies.SpeculativeExecutionPolicy));
            }

            if (profile?.RetryPolicy == null && policies.RetryPolicy == null)
            {
                throw new ArgumentNullException(nameof(policies.ExtendedRetryPolicy));
            }
        }
Ejemplo n.º 7
0
    // Use this for initialization
    void Awake()
    {
        Instance = this;

        // Change an option to show how it should be done
        TimeSpan miliSecForReconnect = TimeSpan.FromMilliseconds(1000);

        SocketOptions options = new SocketOptions();

        options.ReconnectionAttempts = 3;
        options.AutoConnect          = true;
        options.ReconnectionDelay    = miliSecForReconnect;
        options.ConnectWith          = BestHTTP.SocketIO.Transports.TransportTypes.WebSocket;

        // Create the Socket.IO manager
//		url = APIConstants.SOCKET_BASE_URL + "/socket.io/?EIO=3&transport=websocket";
        BestHTTP.HTTPManager.Setup();
        socket = new SocketManager(new Uri(APIConstants.SOCKET_BASE_URL + "/socket.io/"), options);
        BestHTTP.HTTPManager.Setup();

        socket.Socket.On("connect", OnUserConnected);
        socket.Socket.On("disconnect", OnUserDisconnected);

        socket.Socket.On("poker", OnPokerUpdateRequest);
    }
Ejemplo n.º 8
0
        public void Should_Wait_When_ReadTimeout_Is_Zero()
        {
            var testCluster   = TestClusterManager.GetNonShareableTestCluster(1, 1, true, false);
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(0);
            var builder       = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint).WithSocketOptions(socketOptions);

            using (var cluster = builder.Build())
            {
                var session = cluster.Connect();
                var query   = new SimpleStatement("SELECT key FROM system.local");
                //warmup
                TestHelper.Invoke(() => session.Execute(query), 5);
                var task = session.ExecuteAsync(query);
                Thread.Sleep(2000);
                Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);
                //Pause execute and nothing should happen until resume
                testCluster.PauseNode(1);
                task = session.ExecuteAsync(query);
                Thread.Sleep(15000);
                Assert.AreEqual(TaskStatus.WaitingForActivation, task.Status);
                testCluster.ResumeNode(1);
                Thread.Sleep(2000);
                Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);
            }
        }
Ejemplo n.º 9
0
        public void Should_Throw_OperationTimedOutException_When_Retry_Is_False()
        {
            var testCluster   = TestClusterManager.GetNonShareableTestCluster(2, 1, true, false);
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(3000);
            var queryOptions  = new QueryOptions().SetRetryOnTimeout(false);
            var builder       = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint)
                                .WithSocketOptions(socketOptions)
                                .WithQueryOptions(queryOptions);

            using (var cluster = builder.Build())
            {
                var session = cluster.Connect();
                //warmup
                TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
                testCluster.PauseNode(2);
                var coordinators = new HashSet <byte>();
                var exceptions   = new List <OperationTimedOutException>();
                TestHelper.Invoke(() =>
                {
                    try
                    {
                        var rs = session.Execute("SELECT key FROM system.local");
                        coordinators.Add(TestHelper.GetLastAddressByte(rs.Info.QueriedHost));
                    }
                    catch (OperationTimedOutException ex)
                    {
                        exceptions.Add(ex);
                    }
                }, 10);
                testCluster.ResumeNode(2);
                Assert.AreEqual(1, coordinators.Count);
                Assert.AreEqual(5, exceptions.Count);
                Assert.AreEqual(1, coordinators.First());
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SocketOptions"/> class.
 /// </summary>
 private SocketOptions(SocketOptions other)
 {
     BufferSizeKiB = other.BufferSizeKiB;
     KeepAlive     = other.KeepAlive;
     LingerSeconds = other.LingerSeconds;
     TcpNoDelay    = other.TcpNoDelay;
 }
Ejemplo n.º 11
0
        public void Wrong_Ip_Init_Throws_Exception()
        {
            var socketOptions = new SocketOptions();

            socketOptions.SetConnectTimeoutMillis(1000);
            var config = new Configuration(
                new Cassandra.Policies(),
                new ProtocolOptions(),
                new PoolingOptions(),
                socketOptions,
                new ClientOptions(),
                NoneAuthProvider.Instance,
                null,
                new QueryOptions(),
                new DefaultAddressTranslator());

            config.BufferPool = new RecyclableMemoryStreamManager();
            using (var connection = new Connection(new Serializer(GetLatestProtocolVersion()), new IPEndPoint(new IPAddress(new byte[] { 1, 1, 1, 1 }), 9042), config))
            {
                var ex = Assert.Throws <SocketException>(() => TaskHelper.WaitToComplete(connection.Open()));
                Assert.AreEqual(SocketError.TimedOut, ex.SocketErrorCode);
            }
            using (var connection = new Connection(new Serializer(GetLatestProtocolVersion()), new IPEndPoint(new IPAddress(new byte[] { 255, 255, 255, 255 }), 9042), config))
            {
                Assert.Throws <SocketException>(() => TaskHelper.WaitToComplete(connection.Open()));
            }
        }
Ejemplo n.º 12
0
    //int counter = 1;

    public void ConnectToStream()
    {
        SocketOptions options = new SocketOptions();

        options.AutoConnect = false;

        manager = new SocketManager(new Uri("http://fractions01.hcii.cs.cmu.edu:3000/socket.io/"), options);
        //Socket sockChat = manager.GetSocket("/socket.io");
        manager.Socket.On(SocketIOEventTypes.Error, (socket, packet, args) => Debug.LogError(string.Format("Error: {0}", args[0].ToString())));
        manager.Socket.On(SocketIOEventTypes.Connect, OnServerConnect);
        manager.Socket.On(SocketIOEventTypes.Disconnect, OnServerDisconnect);
        manager.Socket.On(SocketIOEventTypes.Error, OnError);
        manager.Socket.On("reconnect", OnReconnect);
        manager.Socket.On("reconnecting", OnReconnecting);
        manager.Socket.On("reconnect_attempt", OnReconnectAttempt);
        manager.Socket.On("reconnect_failed", OnReconnectFailed);

        manager.Socket.On("message", OnMessage);

        manager.Socket.On("update", OnUpdate);
        manager.Socket.On("init", OnInit);

        manager.Socket.On("initBack", OnInitBack);

        manager.Socket.On("error", OnSSError);

        manager.Open();
    }
Ejemplo n.º 13
0
 protected AbstractChannel(SocketOptions options, Binding binding, LetterDeserializer letterDeserializer, HyperletterFactory factory)
 {
     _options            = options;
     _letterDeserializer = letterDeserializer;
     _factory            = factory;
     Binding             = binding;
 }
Ejemplo n.º 14
0
    void Start()
    {
        State = ChatStates.Login;
        SocketOptions options = new SocketOptions();

        options.AutoConnect = false;

        Manager = new SocketManager(new Uri(url), options);
        Socket pvp  = Manager.GetSocket("/pvp");
        Socket news = Manager.GetSocket("/news");

        // Set up custom chat events
//		Manager.Socket.On("server_to_client",server_to_client);

        // The argument will be an Error object.
        pvp.On(SocketIOEventTypes.Error, (socket, packet, args) => Debug.LogError(string.Format("Error: {0}", args[0].ToString())));
        news.On(SocketIOEventTypes.Error, (socket, packet, args) => Debug.LogError(string.Format("Error: {0}", args[0].ToString())));

        // We set SocketOptions' AutoConnect to false, so we have to call it manually.

        pvp.On("OnLogin", OnLogin);
        pvp.On("OnMessage", OnMessage);
        pvp.On("OnJoin", OnJoin);
        news.On("OnMessage", OnMessage);
        Manager.Open();

//		Manager.Socket.On("user joined", OnUserJoined);
//		Manager.Socket.On("user left", OnUserLeft);
//		Manager.Socket.On("typing", OnTyping);
//		Manager.Socket.On("stop typing", OnStopTyping);
    }
Ejemplo n.º 15
0
    void Start()
    {
        // Change an option to show how it should be done
        SocketOptions options = new SocketOptions();

        options.AutoConnect = false;

        // Create the SocketManager instance
        var manager = new SocketManager(new Uri("http://io.weplay.io/socket.io/"), options);

        // Keep a reference to the root namespace
        Socket = manager.Socket;

        // Set up our event handlers.
        Socket.On(SocketIOEventTypes.Connect, OnConnected);
        Socket.On("joined", OnJoined);
        Socket.On("connections", OnConnections);
        Socket.On("join", OnJoin);
        Socket.On("move", OnMove);
        Socket.On("message", OnMessage);
        Socket.On("reload", OnReload);

        // Don't waste cpu cycles on decoding the payload, we are expecting only binary data with this event,
        //  and we can access it through the packet's Attachments property.
        Socket.On("frame", OnFrame, /*autoDecodePayload:*/ false);

        // Add error handler, so we can display it
        Socket.On(SocketIOEventTypes.Error, OnError);

        // We set SocketOptions' AutoConnect to false, so we have to call it manually.
        manager.Open();

        // We are connecting to the server.
        State = States.Connecting;
    }
Ejemplo n.º 16
0
        public void Wrong_Ip_Init_Throws_Exception()
        {
            var socketOptions = new SocketOptions();

            socketOptions.SetConnectTimeoutMillis(1000);
            var config = new Configuration(
                new Cassandra.Policies(),
                new ProtocolOptions(),
                new PoolingOptions(),
                socketOptions,
                new ClientOptions(),
                NoneAuthProvider.Instance,
                null,
                new QueryOptions(),
                new DefaultAddressTranslator(),
                new StartupOptionsFactory(),
                new SessionFactoryBuilder(),
                new Dictionary <string, IExecutionProfile>(),
                new RequestOptionsMapper(),
                null,
                null);

            using (var connection = new Connection(new Serializer(GetProtocolVersion()), config.EndPointResolver.GetOrResolveContactPointAsync(new IPEndPoint(new IPAddress(new byte[] { 1, 1, 1, 1 }), 9042)).Result.Single(), config))
            {
                var ex = Assert.Throws <SocketException>(() => TaskHelper.WaitToComplete(connection.Open()));
                Assert.AreEqual(SocketError.TimedOut, ex.SocketErrorCode);
            }
            using (var connection = new Connection(new Serializer(GetProtocolVersion()), config.EndPointResolver.GetOrResolveContactPointAsync(new IPEndPoint(new IPAddress(new byte[] { 255, 255, 255, 255 }), 9042)).Result.Single(), config))
            {
                Assert.Throws <SocketException>(() => TaskHelper.WaitToComplete(connection.Open()));
            }
        }
Ejemplo n.º 17
0
        private Connection CreateConnection(ProtocolOptions protocolOptions = null, SocketOptions socketOptions = null, PoolingOptions poolingOptions = null)
        {
            if (socketOptions == null)
            {
                socketOptions = new SocketOptions();
            }
            if (protocolOptions == null)
            {
                protocolOptions = new ProtocolOptions();
            }
            var config = new Configuration(
                new Cassandra.Policies(),
                protocolOptions,
                poolingOptions,
                socketOptions,
                new ClientOptions(false, 20000, null),
                NoneAuthProvider.Instance,
                null,
                new QueryOptions(),
                new DefaultAddressTranslator(),
                new StartupOptionsFactory(),
                new SessionFactoryBuilder(),
                new Dictionary <string, IExecutionProfile>(),
                new RequestOptionsMapper(),
                null,
                null);

            return(CreateConnection(GetProtocolVersion(), config));
        }
Ejemplo n.º 18
0
        private Connection CreateConnection(ProtocolOptions protocolOptions = null, SocketOptions socketOptions = null, PoolingOptions poolingOptions = null)
        {
            if (socketOptions == null)
            {
                socketOptions = new SocketOptions();
            }
            if (protocolOptions == null)
            {
                protocolOptions = new ProtocolOptions();
            }
            var config = new Configuration(
                new Cassandra.Policies(),
                protocolOptions,
                poolingOptions,
                socketOptions,
                new ClientOptions(false, 20000, null),
                NoneAuthProvider.Instance,
                null,
                new QueryOptions(),
                new DefaultAddressTranslator());

            config.BufferPool = new RecyclableMemoryStreamManager();
            config.Timer      = new HashedWheelTimer();
            return(CreateConnection(GetLatestProtocolVersion(), config));
        }
Ejemplo n.º 19
0
        public void Should_Not_Leak_Connections_Test()
        {
            _testCluster = SimulacronCluster.CreateNew(1);
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(1).SetConnectTimeoutMillis(1);
            var builder       = Cluster.Builder()
                                .AddContactPoint(_testCluster.InitialContactPoint)
                                .WithSocketOptions(socketOptions);

            var node = _testCluster.GetNodes().First();

            node.DisableConnectionListener(0, "reject_startup").GetAwaiter().GetResult();
            const int length = 1000;

            using (var cluster = builder.Build())
            {
                decimal initialLength = GC.GetTotalMemory(true);
                for (var i = 0; i < length; i++)
                {
                    var ex = Assert.Throws <NoHostAvailableException>(() => cluster.Connect());
                    Assert.AreEqual(1, ex.Errors.Count);
                }
                GC.Collect();
                Thread.Sleep(1000);
                Assert.Less(GC.GetTotalMemory(true) / initialLength, 1.3M,
                            "Should not exceed a 30% (1.3) more than was previously allocated");
            }
        }
Ejemplo n.º 20
0
        public void Should_Move_To_Next_Host_For_Bound_Statements()
        {
            _testCluster = SimulacronCluster.CreateNew(2);
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(500);
            var builder       = Cluster.Builder().AddContactPoint(_testCluster.InitialContactPoint)
                                .WithSocketOptions(socketOptions);

            using (var cluster = builder.Build())
            {
                var session = cluster.Connect();
                var ps      = session.Prepare("SELECT key FROM system.local");
                //warmup
                TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
                var nodes = _testCluster.GetNodes().ToList();
                var node  = nodes[0];
                node.Prime(new
                {
                    when = new { query = "SELECT key FROM system.local" },
                    then = new
                    {
                        result            = "success",
                        delay_in_ms       = 2000,
                        rows              = new[] { new { key = "123" } },
                        column_types      = new { key = "ascii" },
                        ignore_on_prepare = false
                    }
                });
                TestHelper.Invoke(() =>
                {
                    var rs = session.Execute(ps.Bind());
                    Assert.AreEqual(nodes[1].ContactPoint, rs.Info.QueriedHost.ToString());
                }, 10);
            }
        }
Ejemplo n.º 21
0
        public Socket Create(SocketOptions options)
        {
            var socket = !options.AddressType.HasValue
                ? new Socket(SocketType.Stream, ProtocolType.Tcp)
                : new Socket(GetAddressFamily(options.AddressType.Value), SocketType.Stream, ProtocolType.Tcp);

            if (options.UseNagleAlgorithm.HasValue)
            {
                socket.NoDelay = !options.UseNagleAlgorithm.Value;
            }

            if (options.ReceiveBufferSize.HasValue)
            {
                socket.ReceiveBufferSize = options.ReceiveBufferSize.Value;
            }

            if (options.SendBufferSize.HasValue)
            {
                socket.SendBufferSize = options.SendBufferSize.Value;
            }

            if (options.ReceiveTimeoutMs.HasValue)
            {
                socket.ReceiveTimeout = options.ReceiveTimeoutMs.Value;
            }

            if (options.SendTimeoutMs.HasValue)
            {
                socket.SendTimeout = options.SendTimeoutMs.Value;
            }

            return(socket);
        }
Ejemplo n.º 22
0
    void Start()
    {
        // The current state is Login
        State = ChatStates.Login;

        // Change an option to show how it should be done
        SocketOptions options = new SocketOptions();

        options.AutoConnect = false;

        // Create the Socket.IO manager
        Manager = new SocketManager(new Uri("http://chat.socket.io/socket.io/"), options);

        // Set up custom chat events
        Manager.Socket.On("login", OnLogin);
        Manager.Socket.On("new message", OnNewMessage);
        Manager.Socket.On("user joined", OnUserJoined);
        Manager.Socket.On("user left", OnUserLeft);
        Manager.Socket.On("typing", OnTyping);
        Manager.Socket.On("stop typing", OnStopTyping);

        // The argument will be an Error object.
        Manager.Socket.On(SocketIOEventTypes.Error, (socket, packet, args) => Debug.LogError(string.Format("Error: {0}", args[0].ToString())));

        // We set SocketOptions' AutoConnect to false, so we have to call it manually.
        Manager.Open();
    }
Ejemplo n.º 23
0
 protected AbstractChannel(SocketOptions options, Binding binding, LetterDeserializer letterDeserializer, HyperletterFactory factory)
 {
     _options = options;
     _letterDeserializer = letterDeserializer;
     _factory = factory;
     Binding = binding;
 }
Ejemplo n.º 24
0
    public void ConnectSocket()
    {
        TimeSpan e = TimeSpan.FromMilliseconds(1000);

        var options = new SocketOptions();

        options.ReconnectionAttempts = 1000000000;
        options.AutoConnect          = true;
        options.ReconnectionDelay    = e;

        //Server URI
        socketManager = new SocketManager(new Uri(ServerUtils.GetSocketIOUrl()), options);

        //socketManager.GetSocket("/").On ("connect", OnConnect);
        socketManager.Socket.On(SocketIOEventTypes.Error, (socket, packet, args) => Debug.LogError(string.Format("Error: {0}", args[0].ToString())));
        socketManager.Socket.On(SocketIOEventTypes.Disconnect, (socket, packet, eventArgs) => {
            Debug.Log("lose connection");
        });
        socketManager.GetSocket("/").On(SocketIOEventTypes.Connect, (socket, packet, arg) => {
            Debug.Log("Connected");
            var joinRoomReq = new {
                roomNo     = "123456",
                userId     = "1313123",
                clientInfo = Utils.GetClientInfo(),
                userInfo   = Utils.GetUserInfo()
            };

            //BestHTTP.SocketIO.Events.SocketIOAckCallback a = null;
            string json = JsonConvert.SerializeObject(joinRoomReq);
            Debug.Log("jsons = " + json);
            socket.Emit("JoinRoom", JoinRoomCallback, json);
        });
        socketManager.Open();
    }
Ejemplo n.º 25
0
        private async Task <CloudMetadataResult> GetWithHttpClientAsync(
            string url, SocketOptions socketOptions, SSLOptions sslOptions)
        {
            var handler = CreateHttpClientHandler(sslOptions);

            return(await GetWithHandlerAsync(url, handler, socketOptions).ConfigureAwait(false));
        }
Ejemplo n.º 26
0
        long socket(IntPtr jsExecState, long obj, JsValue[] args)
        {
            string name = this.form.Title;
            string url  = args.GetString(jsExecState, 0);
            Dictionary <string, string> options = SocketOptions.options(args.GetString(jsExecState, 1));

            return(JsValue.ObjectValue(jsExecState, new SocketForScript(name, url, options)));
        }
Ejemplo n.º 27
0
        public static PhpResource ConnectServer(string localSocket, out int errno, out string errstr,
                                                double timeout, SocketOptions flags)
        {
            int port = 0;

            //SplitSocketAddressPort(ref localSocket, out port);
            return(Connect(localSocket, port, out errno, out errstr, timeout, flags, StreamContext.Default));
        }
Ejemplo n.º 28
0
        //////////////////////////////////////////////////////////////////////////
        // Socket Options
        //////////////////////////////////////////////////////////////////////////

        public SocketOptions options(TcpSocket fan)
        {
            if (m_options == null)
            {
                m_options = SocketOptions.make(fan);
            }
            return(m_options);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SocketOptions"/> class.
 /// </summary>
 private SocketOptions(SocketOptions other)
 {
     BufferSizeKiB = other.BufferSizeKiB;
     KeepAlive     = other.KeepAlive;
     LingerSeconds = other.LingerSeconds;
     TcpNoDelay    = other.TcpNoDelay;
     ConnectionTimeoutMilliseconds = other.ConnectionTimeoutMilliseconds;
 }
Ejemplo n.º 30
0
        protected async Task <Client> OpenAsync(SocketOptions options)
        {
            this.State.Reset();
            CreateSocket(options);
            await Socket.ConnectAsync();

            return(this);
        }
Ejemplo n.º 31
0
        public static PhpResource ConnectClient(string remoteSocket, out int errno, out string errstr,
                                                double timeout, SocketOptions flags)
        {
            int port;

            SplitSocketAddressPort(ref remoteSocket, out port);
            return(Connect(remoteSocket, port, out errno, out errstr, timeout, flags, StreamContext.Default));
        }
Ejemplo n.º 32
0
 public int GetSockOpt(SocketOptions option)
 {
     int val;
     var rc = NN.GetSockOpt(_socket, option, out val);
     if (rc == -1)
     {
         throw new NanomsgException();
     }
     return val;
 }
Ejemplo n.º 33
0
 internal Configuration(Policies policies,
                      ProtocolOptions protocolOptions,
                      PoolingOptions poolingOptions,
                      SocketOptions socketOptions,
                      ClientOptions clientOptions,
                      IAuthInfoProvider authProvider)
 {
     this._policies = policies;
     this._protocolOptions = protocolOptions;
     this._poolingOptions = poolingOptions;
     this._socketOptions = socketOptions;
     this._clientOptions = clientOptions;
     this._authProvider = authProvider;
 }
Ejemplo n.º 34
0
 public Configuration(Policies policies,
                      ProtocolOptions protocolOptions,
                      PoolingOptions poolingOptions,
                      SocketOptions socketOptions,
                      ClientOptions clientOptions,
                      IAuthInfoProvider authProvider,
                      bool metricsEnabled)
 {
     this._policies = policies;
     this._protocolOptions = protocolOptions;
     this._poolingOptions = poolingOptions;
     this._socketOptions = socketOptions;
     this._clientOptions = clientOptions;
     this._authProvider = authProvider;
     this._metricsEnabled = metricsEnabled;
 }
Ejemplo n.º 35
0
 internal Configuration(Policies policies,
                        ProtocolOptions protocolOptions,
                        PoolingOptions poolingOptions,
                        SocketOptions socketOptions,
                        ClientOptions clientOptions,
                        IAuthProvider authProvider,
                        IAuthInfoProvider authInfoProvider,
                        QueryOptions queryOptions)
 {
     _policies = policies;
     _protocolOptions = protocolOptions;
     _poolingOptions = poolingOptions;
     _socketOptions = socketOptions;
     _clientOptions = clientOptions;
     _authProvider = authProvider;
     _authInfoProvider = authInfoProvider;
     _queryOptions = queryOptions;
 }
Ejemplo n.º 36
0
 public void Should_Move_To_Next_Host_For_Prepare_Requests()
 {
     var testCluster = TestClusterManager.GetNonShareableTestCluster(2, 1, true, false);
     var socketOptions = new SocketOptions().SetReadTimeoutMillis(3000);
     var builder = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint)
         .WithSocketOptions(socketOptions);
     using (var cluster = builder.Build())
     {
         var session = cluster.Connect();
         //warmup
         TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
         testCluster.PauseNode(2);
         TestHelper.Invoke(() =>
         {
             session.Prepare("SELECT key FROM system.local");
         }, 10);
         testCluster.ResumeNode(2);
     }
 }
Ejemplo n.º 37
0
 public void Should_Move_To_Next_Host_For_Simple_Queries()
 {
     var testCluster = TestClusterManager.GetNonShareableTestCluster(2, 1, true, false);
     var socketOptions = new SocketOptions().SetReadTimeoutMillis(3000);
     var builder = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint)
         .WithSocketOptions(socketOptions);
     using (var cluster = builder.Build())
     {
         var session = cluster.Connect();
         //warmup
         TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
         testCluster.PauseNode(2);
         TestHelper.Invoke(() =>
         {
             var rs = session.Execute("SELECT key FROM system.local");
             Assert.AreEqual(1, TestHelper.GetLastAddressByte(rs.Info.QueriedHost));
         }, 10);
         testCluster.ResumeNode(2);
     }
 }
Ejemplo n.º 38
0
        public BatchChannel(SocketOptions options, IChannel channel, BatchLetterBuilder batchBuilder)
        {
            _channel = channel;
            _options = options.Batch;
            _batchBuilder = batchBuilder;

            _channel.ChannelConnected += abstractChannel => ChannelConnected(this);
            _channel.ChannelDisconnected += ChannelOnDisconnected;
            _channel.ChannelQueueEmpty += abstractChannel => {
                                              /* NOOP */
                                          };
            _channel.ChannelInitialized += ChannelOnInitialized;
            _channel.ChannelConnecting += abstractChannel => ChannelConnecting(this);
            _channel.ChannelDisconnecting += (abstractChannel, reason) => ChannelDisconnecting(this, reason);

            _channel.Received += ChannelOnReceived;
            _channel.Sent += ChannelOnSent;
            _channel.FailedToSend += ChannelOnFailedToSend;

            _slidingTimeoutTimer = new Timer(_options.Extend.TotalMilliseconds) {AutoReset = false};
            _slidingTimeoutTimer.Elapsed += SlidingTimeoutTimerOnElapsed;
        }
Ejemplo n.º 39
0
		public static PhpResource ConnectServer(string localSocket, out int errno, out string errstr,
		  double timeout, SocketOptions flags)
		{
			return Connect(localSocket, 0, out errno, out errstr, timeout, flags, StreamContext.Default);
		}
Ejemplo n.º 40
0
		public static PhpResource ConnectClient(string remoteSocket, out int errno, out string errstr,
		  double timeout, SocketOptions flags)
		{
			return Connect(remoteSocket, 0, out errno, out errstr, timeout, flags, StreamContext.Default);
		}
Ejemplo n.º 41
0
		public static PhpResource ConnectClient(string remoteSocket, out int errno, out string errstr,
		  double timeout, SocketOptions flags, PhpResource context)
		{
			StreamContext sc = StreamContext.GetValid(context);
			if (sc == null)
			{
				errno = -1;
				errstr = null;
				return null;
			}

			return Connect(remoteSocket, 0, out errno, out errstr, timeout, flags, sc);
		}
Ejemplo n.º 42
0
        public void TryNextHostRetryPolicyTest()
        {
            ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(2);
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(2000);
            testCluster.Builder = Cluster.Builder()
                                         .WithRetryPolicy(new LoggingRetryPolicy(TryNextHostRetryPolicy.Instance))
                                         .AddContactPoint(testCluster.ClusterIpPrefix + "1")
                                         .AddContactPoint(testCluster.ClusterIpPrefix + "2")
                                         .WithSocketOptions(socketOptions);
            testCluster.InitClient();

            // Setup cluster
            PolicyTestTools policyTestTools = new PolicyTestTools();
            policyTestTools.CreateSchema(testCluster.Session, 2);
            policyTestTools.InitPreparedStatement(testCluster, 12);

            // Try with both hosts
            policyTestTools.Query(testCluster, 10);
            policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + 1 + ":" + DefaultCassandraPort, 5);
            policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + 2 + ":" + DefaultCassandraPort, 5);

            // Try with host 1
            policyTestTools.ResetCoordinators();
            testCluster.PauseNode(2);
            policyTestTools.Query(testCluster, 10);
            policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 1 + ":" + DefaultCassandraPort, 10);
            policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 2 + ":" + DefaultCassandraPort, 0);
            testCluster.ResumeNode(2);

            // Try with host 2
            policyTestTools.ResetCoordinators();
            testCluster.PauseNode(1);
            policyTestTools.Query(testCluster, 10);
            policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 1 + ":" + DefaultCassandraPort, 0);
            policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 2 + ":" + DefaultCassandraPort, 10);

            // Try with 0 hosts
            policyTestTools.ResetCoordinators();
            testCluster.PauseNode(2);
            Assert.Throws<NoHostAvailableException>( () => policyTestTools.Query(testCluster, 10));
            policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 1 + ":" + DefaultCassandraPort, 0);
            policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 2 + ":" + DefaultCassandraPort, 0);

            testCluster.ResumeNode(1);
            testCluster.ResumeNode(2);
        }
Ejemplo n.º 43
0
 public TcpTransport(SocketOptions options)
     : base(options)
 {
     m_endpoints = new Dictionary<Uri, TcpListener>();
 }
Ejemplo n.º 44
0
 //////////////////////////////////////////////////////////////////////////
 // Socket Options
 //////////////////////////////////////////////////////////////////////////
 public SocketOptions options(TcpSocket fan)
 {
     if (m_options == null) m_options = SocketOptions.make(fan);
       return m_options;
 }
Ejemplo n.º 45
0
 public PairProtocol(SocketOptions socketOptions)
     : base(socketOptions)
 {
 }
Ejemplo n.º 46
0
 public OutboundChannel(SocketOptions options, Binding binding, LetterDeserializer letterDeserializer, HyperletterFactory factory)
     : base(options, binding, letterDeserializer, factory)
 {
     _options = options;
 }
Ejemplo n.º 47
0
 /// <summary>
 ///     TODO: I think the string version of this is never needed.
 /// </summary>
 public void SetSockOpt(SocketOptions option, string val)
 {
     var rc = NN.SetSockOpt(_socket, option, val);
     if (rc < 0)
     {
         throw new NanomsgException();
     }
 }
Ejemplo n.º 48
0
		public static PhpResource ConnectClient(string remoteSocket, out int errno, out string errstr,
		  double timeout, SocketOptions flags)
		{
			int port = 0;
			//SplitSocketAddressPort(ref remoteSocket, out port);
			return Connect(remoteSocket, port, out errno, out errstr, timeout, flags, StreamContext.Default);
		}
Ejemplo n.º 49
0
 public BatchLetterBuilder(SocketOptions socketOptions, LetterSerializer serializer)
 {
     _maxLetters = socketOptions.Batch.MaxLetters;
     _serializer = serializer;
 }
Ejemplo n.º 50
0
 public TypedSocketOptions()
 {
     Socket = new SocketOptions();
     AnswerTimeout = TimeSpan.FromSeconds(10);
 }
Ejemplo n.º 51
0
 public void Should_Throw_NoHostAvailableException_When_All_Hosts_Down()
 {
     var testCluster = TestClusterManager.GetNonShareableTestCluster(2, 1, true, false);
     var socketOptions = new SocketOptions().SetReadTimeoutMillis(3000);
     var builder = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint)
         .WithSocketOptions(socketOptions);
     using (var cluster = builder.Build())
     {
         var session = cluster.Connect();
         //warmup
         TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
         testCluster.PauseNode(1);
         testCluster.PauseNode(2);
         Assert.Throws<NoHostAvailableException>(() => session.Execute("SELECT key FROM system.local"));
         testCluster.ResumeNode(1);
         testCluster.ResumeNode(2);
     }
 }
Ejemplo n.º 52
0
 public void Should_Throw_OperationTimedOutException_When_Retry_Is_False()
 {
     var testCluster = TestClusterManager.GetNonShareableTestCluster(2, 1, true, false);
     var socketOptions = new SocketOptions().SetReadTimeoutMillis(3000);
     var queryOptions = new QueryOptions().SetRetryOnTimeout(false);
     var builder = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint)
         .WithSocketOptions(socketOptions)
         .WithQueryOptions(queryOptions);
     using (var cluster = builder.Build())
     {
         var session = cluster.Connect();
         //warmup
         TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
         testCluster.PauseNode(2);
         var coordinators = new HashSet<byte>();
         var exceptions = new List<OperationTimedOutException>();
         TestHelper.Invoke(() =>
         {
             try
             {
                 var rs = session.Execute("SELECT key FROM system.local");
                 coordinators.Add(TestHelper.GetLastAddressByte(rs.Info.QueriedHost));
             }
             catch (OperationTimedOutException ex)
             {
                 exceptions.Add(ex);
             }
         }, 10);
         testCluster.ResumeNode(2);
         Assert.AreEqual(1, coordinators.Count);
         Assert.AreEqual(5, exceptions.Count);
         Assert.AreEqual(1, coordinators.First());
     }
 }
Ejemplo n.º 53
0
        public void Should_Use_Statement_ReadTimeout()
        {
            const int generalReadTimeout = 1500;
            const int statementReadTimeout = 12000;
            var testCluster = TestClusterManager.CreateNew();
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(generalReadTimeout);
            var queryOptions = new QueryOptions().SetRetryOnTimeout(false);
            var builder = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint)
                .WithSocketOptions(socketOptions)
                .WithPoolingOptions(new PoolingOptions()
                    .SetCoreConnectionsPerHost(HostDistance.Local, 1)
                    .SetHeartBeatInterval(0))
                .WithQueryTimeout(Timeout.Infinite)
                .WithQueryOptions(queryOptions);
            using (var cluster = builder.Build())
            {
                var session = cluster.Connect();
                //warmup
                TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
                testCluster.PauseNode(1);
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                Assert.Throws<OperationTimedOutException>(() => session.Execute("SELECT key FROM system.local"));
                stopWatch.Stop();
                //precision of the timer is not guaranteed
                Assert.Greater(stopWatch.ElapsedMilliseconds, generalReadTimeout - 1000);
                Assert.Less(stopWatch.ElapsedMilliseconds, generalReadTimeout + 1000);

                //Try with an specified timeout at Statement level
                var stmt = new SimpleStatement("SELECT key FROM system.local")
                    .SetReadTimeoutMillis(statementReadTimeout);
                stopWatch.Restart();
                Assert.Throws<OperationTimedOutException>(() => session.Execute(stmt));
                stopWatch.Stop();
                //precision of the timer is not guaranteed
                Assert.Greater(stopWatch.ElapsedMilliseconds, statementReadTimeout - 3000);
                Assert.Less(stopWatch.ElapsedMilliseconds, statementReadTimeout + 3000);
                testCluster.ResumeNode(1);
            }
        }
Ejemplo n.º 54
0
 public void Should_Wait_When_ReadTimeout_Is_Zero()
 {
     var testCluster = TestClusterManager.GetNonShareableTestCluster(1, 1, true, false);
     var socketOptions = new SocketOptions().SetReadTimeoutMillis(0);
     var builder = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint).WithSocketOptions(socketOptions);
     using (var cluster = builder.Build())
     {
         var session = cluster.Connect();
         var query = new SimpleStatement("SELECT key FROM system.local");
         //warmup
         TestHelper.Invoke(() => session.Execute(query), 5);
         var task = session.ExecuteAsync(query);
         Thread.Sleep(2000);
         Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);
         //Pause execute and nothing should happen until resume
         testCluster.PauseNode(1);
         task = session.ExecuteAsync(query);
         Thread.Sleep(15000);
         Assert.AreEqual(TaskStatus.WaitingForActivation, task.Status);
         testCluster.ResumeNode(1);
         Thread.Sleep(2000);
         Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);
     }
 }
Ejemplo n.º 55
0
 public InboundChannel(SocketOptions options, Socket socket, Binding binding, LetterDeserializer letterDeserializer, HyperletterFactory factory)
     : base(options, binding, letterDeserializer, factory)
 {
     Socket = socket;
 }
Ejemplo n.º 56
0
		public static PhpResource ConnectServer(string localSocket, out int errno, out string errstr,
		  double timeout, SocketOptions flags, PhpResource context)
		{
			StreamContext sc = StreamContext.GetValid(context);
			if (sc == null)
			{
				errno = -1;
				errstr = null;
				return null;
			}

			int port;
			SplitSocketAddressPort(ref localSocket, out port);
			return Connect(localSocket, port, out errno, out errstr, timeout, flags, sc);
		}
Ejemplo n.º 57
0
		public static PhpResource ConnectServer(string localSocket, out int errno, out string errstr,
		  double timeout, SocketOptions flags)
		{
			int port;
			SplitSocketAddressPort(ref localSocket, out port);
			return Connect(localSocket, port, out errno, out errstr, timeout, flags, StreamContext.Default);
		}
Ejemplo n.º 58
0
 public BaseTransport(SocketOptions options)
     : base(options)
 {
 }
Ejemplo n.º 59
0
		/// <summary>
		/// Opens a new SocketStream
		/// </summary>
		internal static SocketStream Connect(string remoteSocket, int port, out int errno, out string errstr,
		  double timeout, SocketOptions flags, StreamContext/*!*/ context)
		{
			errno = 0;
			errstr = null;

			if (remoteSocket == null)
			{
				PhpException.ArgumentNull("remoteSocket");
				return null;
			}

			// TODO: extract schema (tcp://, udp://) and port from remoteSocket
			// Uri uri = Uri.TryCreate(remoteSocket);
			ProtocolType protocol = ProtocolType.Tcp;

			if (Double.IsNaN(timeout))
				timeout = Configuration.Local.FileSystem.DefaultSocketTimeout;

			// TODO:
			if (flags != SocketOptions.None && flags != SocketOptions.Asynchronous)
				PhpException.ArgumentValueNotSupported("flags", (int)flags);

			try
			{
                // workitem 299181; for remoteSocket as IPv4 address it results in IPv6 address
                //IPAddress address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];
                
                IPAddress address;
                if (!IPAddress.TryParse(remoteSocket, out address)) // if remoteSocket is not a valid IP address then lookup the DNS
                    address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];

				Socket socket = new Socket(address.AddressFamily, SocketType.Stream, protocol);

				IAsyncResult res = socket.BeginConnect(
				  new IPEndPoint(address, port),
				  new AsyncCallback(StreamSocket.ConnectResultCallback),
				  socket);

				int msec = 0;
				while (!res.IsCompleted)
				{
					Thread.Sleep(100);
					msec += 100;
					if (msec / 1000.0 > timeout)
					{
						PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_timeout",
						  FileSystemUtils.StripPassword(remoteSocket)));
						return null;
					}
				}
				socket.EndConnect(res);

				//        socket.Connect(new IPEndPoint(address, port));
				return new SocketStream(socket, remoteSocket, context, (flags & SocketOptions.Asynchronous) == SocketOptions.Asynchronous);
			}
			catch (SocketException e)
			{
				errno = e.ErrorCode;
				errstr = e.Message;
			}
			catch (System.Exception e)
			{
				errno = -1;
				errstr = e.Message;
			}

			PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_error",
			  FileSystemUtils.StripPassword(remoteSocket), errstr));
			return null;
		}
Ejemplo n.º 60
0
 public TcpListener(SocketOptions options)
     : base(options)
 {
 }