public void GeneralPropertyCheck() { var fakeSocket = new FakeWebSocket( WebSocketState.Aborted, WebSocketCloseStatus.EndpointUnavailable, "close desc", "sub proto"); var context = new DefaultHttpContext(); var provider = new Mock <IServiceProvider>().Object; var user = new ClaimsPrincipal(); context.RequestServices = provider; context.User = user; var array = new ArraySegment <byte>(new byte[500]); var client = new WebSocketClientConnection(fakeSocket, context); Assert.AreEqual(ClientConnectionState.Aborted, client.State); Assert.AreEqual(ClientConnectionCloseStatus.EndpointUnavailable, client.CloseStatus.Value); Assert.AreEqual("close desc", client.CloseStatusDescription); Assert.AreEqual(provider, client.ServiceProvider); Assert.AreEqual(user, client.User); }
public static void Initialize(WebSocketClientConnection connection) { if (instance == null) { instance = new GameObject("WebSocket Listener").AddComponent <WebSocketUnityUpdater>(); } instance.connection = connection; }
public async Task SuccessfulCLose_HasSentToSocket() { var fakeSocket = new FakeWebSocket(); var array = new ArraySegment <byte>(new byte[500]); var client = new WebSocketClientConnection(fakeSocket, new DefaultHttpContext()); await client.CloseAsync(ClientConnectionCloseStatus.Empty, string.Empty, default); Assert.AreEqual(1, fakeSocket.TotalCloseCalls); }
public async Task SuccessfulSend_HasSentToSocket() { var fakeSocket = new FakeWebSocket(); var array = new ArraySegment <byte>(new byte[500]); var client = new WebSocketClientConnection(fakeSocket, new DefaultHttpContext()); await client.SendAsync(array, ClientMessageType.Binary, true, default); Assert.AreEqual(1, fakeSocket.TotalCallsToSend); }
public async Task SuccessfulRecieve_HasRecievedFromSocket() { var fakeSocket = new FakeWebSocket(); var array = new ArraySegment <byte>(new byte[500]); var client = new WebSocketClientConnection(fakeSocket, new DefaultHttpContext()); var result = await client.ReceiveAsync(array, default); Assert.AreEqual(1, fakeSocket.TotalCallsToReceive); }
/// <summary> /// The invocation method that can process the current http context /// if it should be handled as a subscription request. /// </summary> /// <param name="context">The context.</param> /// <returns>Task.</returns> public virtual async Task InvokeAsync(HttpContext context) { // immediate bypass if not aimed at this schema subscription route var isListeningToPath = string.Compare( context.Request.Path, _routePath, CultureInfo.InvariantCulture, CompareOptions.OrdinalIgnoreCase) == 0; if (isListeningToPath && context.WebSockets.IsWebSocketRequest) { var logger = context.RequestServices.GetService <IGraphEventLogger>(); try { var webSocket = await context.WebSockets.AcceptWebSocketAsync( SubscriptionConstants.WebSockets.DEFAULT_SUB_PROTOCOL) .ConfigureAwait(false); IClientConnection socketProxy = new WebSocketClientConnection(webSocket, context); var subscriptionClient = await _subscriptionServer .RegisterNewClient(socketProxy) .ConfigureAwait(false); if (subscriptionClient != null) { logger?.SubscriptionClientRegistered(_subscriptionServer, subscriptionClient); // hold the client connection to keep the socket open await subscriptionClient.StartConnection().ConfigureAwait(false); logger?.SubscriptionClientDropped(subscriptionClient); } } catch (Exception ex) { logger?.UnhandledExceptionEvent(ex); if (!context.Response.HasStarted) { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; await context.Response.WriteAsync( "An unexpected error occured attempting to configure the web socket connection. " + "Check the server event logs for further details.") .ConfigureAwait(false); } } return; } await _next(context).ConfigureAwait(false); }
public void Connect(Uri uri) { _connection = new WebSocketClientSSLConnection(_cacert, _wsMessageHandler); _connection.ConnectionClose += _wsMessageHandler.OnClose; _connection.ConnectionClose += delegate { OnDisconnect(EventArgs.Empty); }; _connection.ConnectionOpen += _wsMessageHandler.OnOpen; _connection.ConnectionOpen += delegate { OnConnect(EventArgs.Empty); }; // we no longer do it this way, but process it via a called function on full text being read //_connection.ConnectionRead += _wsMessageHandler.onMessage; // this whole starting of another thread to run the connection is because sometimes the connection hangs. We have set the read timeout // on the connection to 5 mins, but lets watch it here as well to make sure that the whole connection system doesn't hang. bool connected = false; Thread startThread = new Thread(() => { try { if (!_connection.Start(uri.Host, uri.Port.ToString(), uri.PathAndQuery, true, "", Protocol)) { throw new IOException("Unknown error connecting to " + uri.ToString()); } connected = true; } catch (Exception e) { Logger.Error("Failed to connect to server [" + uri + "] : " + e.Message); } }) { Name = "ConnectionStarter" }; startThread.Start(); if (!startThread.Join(360000))// 6 minute timeout { startThread.Abort(); // connect didn't come back within the timeout period throw new Exception("Failed to start connection within timeout"); } if (!connected) { throw new IOException("Failed to connect to server [" + uri + "]"); } Logger.Debug("Connection Complete"); //OnConnect(new EventArgs()); }
public async Task Receive_ThrowsGeneralException_ReturnsConnectionFailureResult() { var fakeSocket = new FakeWebSocket(); var exceptionThrown = new Exception("total failure"); fakeSocket.ThrowExceptionOnReceieve(exceptionThrown); var array = new ArraySegment <byte>(new byte[500]); var client = new WebSocketClientConnection(fakeSocket, new DefaultHttpContext()); var result = await client.ReceiveAsync(array, default); var failureResult = result as ClientConnectionFailureResult; Assert.IsNotNull(failureResult); Assert.AreEqual(exceptionThrown, failureResult.Exception); }
public void Connect() { _messageHandler = new CoupledWebSocketMessageHandler(this); _connection = new WebSocketClientSSLConnection(_cert, _messageHandler); _connection.ConnectionClose += _messageHandler.OnClose; _connection.ConnectionClose += delegate { OnDisconnected(); }; _connection.ConnectionOpen += _messageHandler.OnOpen; _connection.ConnectionOpen += delegate { OnConnected(); }; _connection.ConnectionReadFull += ProcessStream; try { if (!_connection.Start(_uri.Host, _uri.Port.ToString(), _uri.PathAndQuery, true, "", "message")) { throw new IOException("Unknown error connecting to " + _uri); } _connection.SendText(_uniqueId); } catch (Exception e) { Logger.Error("Failed to connect to server [" + _uri + "] : " + e.Message); throw new IOException("Failed to connect to server [" + _uri + "] : " + e.Message, e); } }
public void ConnectToRelay() { IPAddress ipAddress; if (!IPAddress.TryParse(relayIP, out ipAddress)) { ipAddress = Dns.GetHostEntry(relayIP).AddressList[0]; } drClient = GetComponent <UnityClient>(); directConnectModule = GetComponent <DarkMirrorDirectConnectModule>(); if (drClient.ConnectionState == ConnectionState.Disconnected) { if (useWebsockets) { websocketClient = new WebSocketClientConnection(relayIP, relayPort); if (Application.platform != RuntimePlatform.WebGLPlayer) { drClient.Client.ConnectInBackground(websocketClient); } else { drClient.Client.Connect(websocketClient); } } else { drClient.Client.Connect(IPAddress.Parse(ipAddress.ToString()), relayPort, true); } } drClient.Disconnected += Client_Disconnected; drClient.MessageReceived += Client_MessageReceived; }
public Task<IConnection> Connect(string endpoint) { if (this._socket == null && !this._connecting) { this._connecting = true; try { var webSocket = new WebSocket(endpoint + "/"); //try //{ this.ConnectSocket(webSocket); this._socket = webSocket; //} //catch(Exception ex) //{ // webSocket = new WebSocket("ws://" + endpoint); //} //if (this._socket == null) //{ // this.ConnectSocket(webSocket); //} var connection = this.CreateNewConnection(this._socket); this._connectionManager.NewConnection(connection); var action = this.ConnectionOpened; if (action != null) { action(connection); } this._connection = connection; return TaskHelper.FromResult<IConnection>(connection); } finally { this._connecting = false; } } else { throw new InvalidOperationException("This transport is already connected."); } }
void Start() { ws = new AppWebSocketConnection(state); ws.ConnectionOpen += ConnectionOpen; bool useSsl = false; ws.Start("localhost", "2000", "/", useSsl); //ws.Start("coffeepong.jit.su", "80", "/", useSsl); }
public override void Start() { c = new WebSocketClientConnection(); }