コード例 #1
0
        /// <summary>
        /// Asynchronously opens the WebSocket connection.
        /// </summary>
        /// <returns><c>true</c> if the socket was successfully opened; <c>false</c> otherwise.</returns>
        public async Task <bool> OpenAsync()
        {
            if (IsWebSocketOpen)
            {
                return(true);
            }

            Logger.Trace(Log("Opening web socket connection..."));

            var token = ReceiveLoopToken;

            try
            {
                //////////////////////////////////////////////////////////////////////
                // Work around to avoid websocket connections timing out
                // based on https://stackoverflow.com/questions/40502921

                var prevIdleTime = ServicePointManager.MaxServicePointIdleTime;
                ServicePointManager.MaxServicePointIdleTime = Timeout.Infinite;

                // End work around
                //////////////////////////////////////////////////////////////////////

                await ClientSocket.ConnectAsync(Uri, token).ConfigureAwait(CaptureAsyncContext);

                //////////////////////////////////////////////////////////////////////
                // Work around based on https://stackoverflow.com/questions/40502921

                ServicePointManager.MaxServicePointIdleTime = prevIdleTime;

                // End work around
                //////////////////////////////////////////////////////////////////////

                Logger.Verbose($"Connected to {Uri}");
            }
            catch (OperationCanceledException)
            {
                Logger.Verbose($"Connection to {Uri} cancelled.");
                return(false);
            }

            if (!IsWebSocketOpen)
            {
                return(false);
            }

            if (token.IsCancellationRequested)
            {
                return(false);
            }

            RaiseSocketOpened();

            Logger.Trace(Log("Requesting session..."));
            await RequestSessionAsync().ConfigureAwait(CaptureAsyncContext);

            StartReceiveLoop();

            return(true);
        }
コード例 #2
0
 public bool Connect(string _host, int _port)
 {
     this.Close();
     host   = _host;
     port   = _port;
     socket = new ClientSocket(host, port);
     return(socket.ConnectAsync(OnSocketOpen, OnSocketRecvData, OnSocketClose));
 }
コード例 #3
0
 public void ConnectAsync(string ip, ushort port)
 {
     ThreadedConsole.WriteLine("Connecting to Server...");
     ReceiveQueue.Start(OnPacket);
     Socket = new ClientSocket(this);
     Socket.OnDisconnect += Disconnected;
     Socket.OnConnected  += Connected;
     Socket.ConnectAsync(ip, port);
 }
コード例 #4
0
ファイル: Client.cs プロジェクト: Alumniminium/Chat
        public void ConnectAsync(string user, string pass)
        {
            User = user;
            Pass = pass;
            Universal.IO.Sockets.Queues.ReceiveQueue.OnPacket = OnPacket;

            Socket = new ClientSocket(this);
            Socket.OnDisconnect += Disconnected;
            Socket.OnConnected  += Connected;
            Socket.ConnectAsync(Core.StateFile.ServerIP, Core.StateFile.Port);
        }
コード例 #5
0
ファイル: ClientSocketTests.cs プロジェクト: liyuj/ignite-3
        public async Task TestConnectAndSendRequestWithInvalidOpCodeThrowsError()
        {
            using var socket = await ClientSocket.ConnectAsync(new IPEndPoint (IPAddress.Loopback, ServerPort), new());

            using var requestWriter = new PooledArrayBufferWriter();
            requestWriter.GetMessageWriter().Write(123);

            var ex = Assert.ThrowsAsync <IgniteClientException>(
                async() => await socket.DoOutInOpAsync((ClientOp)1234567, requestWriter));

            Assert.AreEqual("Unexpected operation code: 1234567", ex !.Message);
        }
コード例 #6
0
        /// <summary>
        /// Open a socket connection
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="requestHeaders">Optional headers to send with the request</param>
        /// <returns></returns>
        public async Task OpenAsync(Uri uri, Dictionary <string, string> requestHeaders = null)
        {
            await ClientSocket.ConnectAsync(uri, CancellationToken.None);

            if (ClientSocket.State != WebSocketState.Open)
            {
                throw new Exception("Failed to open connection");
            }

            await OnConnected();

            _listening = Task.Run(Listen);
        }
コード例 #7
0
ファイル: ClientSocketTests.cs プロジェクト: liyuj/ignite-3
        public async Task TestDisposedSocketThrowsExceptionOnSend()
        {
            var socket = await ClientSocket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ServerPort), new());

            socket.Dispose();

            using var requestWriter = new PooledArrayBufferWriter();
            requestWriter.GetMessageWriter().Write(123);

            Assert.ThrowsAsync <ObjectDisposedException>(
                async() => await socket.DoOutInOpAsync(ClientOp.SchemasGet, requestWriter));

            // Multiple dispose is allowed.
            socket.Dispose();
        }
コード例 #8
0
ファイル: Client.cs プロジェクト: Alumniminium/AlumniDNS
        public Task <bool> ConnectAsync(string ip, ushort port)
        {
            Socket = new ClientSocket(this);
            ReceiveQueue.Start(OnPacket);

            var tcs = new TaskCompletionSource <bool>();

            Socket.OnConnected  += () => { tcs?.SetResult(true); };
            Socket.OnDisconnect += () => { tcs?.SetResult(false); };

            Socket.OnDisconnect += Disconnected;
            Socket.OnConnected  += Connected;
            Socket.ConnectAsync(ip, port);
            return(tcs.Task);
        }
コード例 #9
0
ファイル: Client.cs プロジェクト: Patrikkk-zz/TemplateProxy
        public void Connect()
        {
            RecSendAsyncEventArgs = new SocketAsyncEventArgs();

            RecSendAsyncEventArgs.UserToken      = ClientSocket;
            RecSendAsyncEventArgs.RemoteEndPoint = HostEndPoint;
            RecSendAsyncEventArgs.Completed     += new EventHandler <SocketAsyncEventArgs>(IO_Completed);

            bool willRaiseEvent = ClientSocket.ConnectAsync(RecSendAsyncEventArgs);

            if (!willRaiseEvent)
            {
                ProcessConnect(RecSendAsyncEventArgs);
            }
        }
コード例 #10
0
ファイル: Listener.cs プロジェクト: zwurv/nem2-sdk-csharp
        /// <summary>
        /// Opens the websocket connection.
        /// </summary>
        /// <returns>IObservable&lt;System.Boolean&gt;.</returns>
        public IObservable <bool> Open()
        {
            return(Observable.Start(() =>
            {
                ClientSocket.ConnectAsync(new Uri(string.Concat("ws://", Domain, ":", Port, "/ws")), CancellationToken.None)
                .GetAwaiter()
                .GetResult();

                Uid = JsonConvert.DeserializeObject <WebsocketUID>(ReadSocket().Result);

                LoopReads = Task.Run(() => LoopRead());

                Console.WriteLine("Connected to websocket via domain: " + Domain);

                return Uid != null;
            }));
        }
コード例 #11
0
ファイル: ClientSocketTests.cs プロジェクト: liyuj/ignite-3
        public async Task TestConnectAndSendRequestReturnsResponse()
        {
            using var socket = await ClientSocket.ConnectAsync(new IPEndPoint (IPAddress.Loopback, ServerPort), new());

            using var requestWriter = new PooledArrayBufferWriter();

            WriteString(requestWriter.GetMessageWriter(), "non-existent-table");

            using var response = await socket.DoOutInOpAsync(ClientOp.TableGet, requestWriter);

            Assert.IsTrue(response.GetReader().IsNil);

            void WriteString(MessagePackWriter writer, string str)
            {
                writer.WriteString(Encoding.UTF8.GetBytes(str));
                writer.Flush();
            }
        }
コード例 #12
0
        /// <summary>
        /// Asynchronously opens the WebSocket connection.
        /// </summary>
        public async Task <bool> OpenAsync()
        {
            if (IsOpen)
            {
                return(true);
            }

            Logger.Trace(Log("Opening web socket connection..."));

            _source = new CancellationTokenSource();
            var token = _source.Token;

            try
            {
                await ClientSocket.ConnectAsync(Uri, token);

                Logger.Verbose($"Connected to {Uri}");
            }
            catch (OperationCanceledException)
            {
                Logger.Verbose($"Connection to {Uri} cancelled.");
                return(false);
            }

            if (!IsOpen)
            {
                return(false);
            }

            if (token.IsCancellationRequested)
            {
                return(false);
            }

            _connectionHandlingTask = Task.Run(async() => await HandleConnection(token), token);

            Logger.Trace(Log("Requesting session..."));
            Adapter.RequestSession(this, ApplicationName, ApplicationVersion, _supportedCompression);

            return(true);
        }
コード例 #13
0
        private void StartConnect(SocketAsyncEventArgs e)
        {
            SetHeartBeat();//设置心跳参数
            TimeoutObject.Reset();

            if (e == null)
            {
                e = new SocketAsyncEventArgs()
                {
                    RemoteEndPoint = iPEndPoint
                };
                e.Completed += ConnectEventArg_Completed;
                e.UserToken  = this;
            }

            bool willRaiseEvent = ClientSocket.ConnectAsync(e);

            //如果没有挂起
            if (!willRaiseEvent)
            {
                ProcessConnect(e);
            }

            if (TimeoutObject.WaitOne(5000, false))//返回true为TimeoutObject.set(), 返回false为timeout
            {
                if (IsConnected)
                {
                    connectSucess?.Invoke(this, e);
                }
                else
                {
                    connectError?.Invoke(this, e);
                }
            }
            else
            {
                Close(null);
                e.SocketError = SocketError.TimedOut;
                connectError?.Invoke(this, e);
            }
        }
コード例 #14
0
        /// <summary>
        ///     Opens the websocket connection.
        /// </summary>
        /// <returns>IObservable&lt;System.Boolean&gt;.</returns>
        public IObservable <bool> Open()
        {
            return(Observable.Start(() =>
            {
                if (ClientSocket.State != WebSocketState.Open)
                {
                    var protocol = UseSsl ? "wss://" : "ws://";
                    var protocolPath = "/ws";
                    ClientSocket.ConnectAsync(new Uri(string.Concat(protocol, Domain, ":", Port, protocolPath)),
                                              CancellationToken.None)
                    .GetAwaiter()
                    .GetResult();

                    Uid = JsonConvert.DeserializeObject <WebsocketUid>(ReadSocket().Result);

                    LoopReads = Task.Run(() => LoopRead(), _cToken.Token);

                    Console.WriteLine("Connected to websocket via domain: " + Domain);
                }

                return Uid != null;
            }));
        }
コード例 #15
0
ファイル: ClientSocketTests.cs プロジェクト: liyuj/ignite-3
 public void TestConnectWithoutServerThrowsException()
 {
     Assert.CatchAsync(async() => await ClientSocket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 569), new()));
 }
コード例 #16
0
        /// <summary>
        /// Asynchronously opens the WebSocket connection.
        /// </summary>
        public async Task <bool> OpenAsync()
        {
            if (IsOpen)
            {
                return(true);
            }

            Logger.Trace(Log("Opening web socket connection..."));

            _source = new CancellationTokenSource();
            var token = _source.Token;

            try
            {
                //////////////////////////////////////////////////////////////////////
                // Work around based on https://stackoverflow.com/questions/40502921

                var prevIdleTime = ServicePointManager.MaxServicePointIdleTime;
                ServicePointManager.MaxServicePointIdleTime = Timeout.Infinite;

                // End work around
                //////////////////////////////////////////////////////////////////////

                await ClientSocket.ConnectAsync(Uri, token).ConfigureAwait(CaptureAsyncContext);

                //////////////////////////////////////////////////////////////////////
                // Work around based on https://stackoverflow.com/questions/40502921

                ServicePointManager.MaxServicePointIdleTime = prevIdleTime;

                // End work around
                //////////////////////////////////////////////////////////////////////

                Logger.Verbose($"Connected to {Uri}");
            }
            catch (OperationCanceledException)
            {
                Logger.Verbose($"Connection to {Uri} cancelled.");
                return(false);
            }

            if (!IsOpen)
            {
                return(false);
            }

            if (token.IsCancellationRequested)
            {
                return(false);
            }

            _connectionHandlingTask = Task.Factory.StartNew(
                async() => await HandleConnection(token).ConfigureAwait(CaptureAsyncContext), token,
                TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach,
                TaskScheduler.Default).Unwrap();

            Logger.Trace(Log("Requesting session..."));
            Adapter.RequestSession(this, ApplicationName, ApplicationVersion, _supportedCompression);

            InvokeSocketOpened();

            return(true);
        }