System.Net.WebSockets.ClientWebSocket.ConnectAsync C# (CSharp) Method

ConnectAsync() public method

public ConnectAsync ( Uri uri, CancellationToken cancellationToken ) : Task
uri Uri
cancellationToken System.Threading.CancellationToken
return Task
        public Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }
            if (!uri.IsAbsoluteUri)
            {
                throw new ArgumentException(SR.net_uri_NotAbsolute, nameof(uri));
            }
            if (uri.Scheme != UriScheme.Ws && uri.Scheme != UriScheme.Wss)
            {
                throw new ArgumentException(SR.net_WebSockets_Scheme, nameof(uri));
            }

            // Check that we have not started already
            var priorState = (InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connecting, (int)InternalState.Created);
            if (priorState == InternalState.Disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }
            else if (priorState != InternalState.Created)
            {
                throw new InvalidOperationException(SR.net_WebSockets_AlreadyStarted);
            }
            _options.SetToReadOnly();

            return ConnectAsyncCore(uri, cancellationToken);
        }

Same methods

ClientWebSocket::ConnectAsync ( System uri, System cancellationToken ) : System.Threading.Tasks.Task

Usage Example

示例#1
5
文件: Program.cs 项目: leloulight/dnx
        private void TestWebSockets()
        {
            var socket = new ClientWebSocket();
            Console.WriteLine("Connecting");
            socket.ConnectAsync(new Uri("wss://echo.websocket.org"), CancellationToken.None).Wait();

            Console.WriteLine("Sending");
            socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello")), WebSocketMessageType.Text, true, CancellationToken.None).Wait();

            var buffer = new byte[1024];
            Console.WriteLine("Receiving");
            var result = socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;

            Console.WriteLine($"Recieved: {Encoding.UTF8.GetString(buffer, 0, result.Count)}");
        }
All Usage Examples Of System.Net.WebSockets.ClientWebSocket::ConnectAsync