/// <summary> /// The functions will connect the client to the specified websocket server. /// </summary> /// <param name="uri">The string represention of the uri of the web server to connect to.</param> public void Connect(string uri) { if (_status != WebSocketStatus.CLOSED) { return; } try { _status = WebSocketStatus.CONNECTING; _uri = new Uri(uri); var webSocketHandshake = new WebSocketHandshake(_uri, SubProtocol.ToString(), WebSocketConstants.WS_VERSION_DEFAULT); if (_socket != null && _socket.Connected) { _socket.Close(); } var scheme = _uri.Scheme; var port = _uri.Port; var host = _uri.Host; _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.NoDelay = true; var hostEntry = new DnsEndPoint(host, port); // Create a SocketAsyncEventArgs object to be used in the connection request var socketEventArg = new SocketAsyncEventArgs(); socketEventArg.RemoteEndPoint = hostEntry; socketEventArg.Completed += (sender, args) => { if (args.SocketError == SocketError.Success) { webSocketHandshake.PerformHandShakeWithServer(_socket, HandshakeCompleted, HandshakeFailed); } else { ProcessSocketError(args.SocketError); } }; _socket.ConnectAsync(socketEventArg); } catch (Exception ex) { var webSocketErrorArgs = new WebSocketErrorEventArgs { ErrorType = WebSocketExceptionType.UNABLE_TO_CONNECT, Message = ex.Message }; OnError(webSocketErrorArgs); } }
/// <summary> /// The functions will connect the client to the specified websocket server. /// </summary> /// <param name="uri">The string represention of the uri of the web server to connect to.</param> public void Connect(string uri) { if (_status != WebSocketStatus.CLOSED) { return; } try { _status = WebSocketStatus.CONNECTING; _uri = new Uri(uri); var webSocketHandshake = new WebSocketHandshake(_uri, SubProtocol.ToString(), WebSocketConstants.WS_VERSION_DEFAULT); if (_socket != null && _socket.Connected) _socket.Close(); var scheme = _uri.Scheme; var port = _uri.Port; var host = _uri.Host; _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.NoDelay = true; var hostEntry = new DnsEndPoint(host, port); // Create a SocketAsyncEventArgs object to be used in the connection request var socketEventArg = new SocketAsyncEventArgs(); socketEventArg.RemoteEndPoint = hostEntry; socketEventArg.Completed += (sender, args) => { if (args.SocketError == SocketError.Success) { webSocketHandshake.PerformHandShakeWithServer(_socket, HandshakeCompleted, HandshakeFailed); } else { ProcessSocketError(args.SocketError); } }; _socket.ConnectAsync(socketEventArg); } catch (Exception ex) { var webSocketErrorArgs = new WebSocketErrorEventArgs { ErrorType = WebSocketExceptionType.UNABLE_TO_CONNECT, Message = ex.Message }; OnError(webSocketErrorArgs); } }