/// <summary> /// Return WebSocket connection state. /// </summary> /// <returns>The state.</returns> public WebSocketState GetState() { int state = WebSocketGetState(this.instanceId); if (state < 0) { throw WebSocketHelpers.GetErrorMessageFromCode(state, null); } switch (state) { case 0: return(WebSocketState.Connecting); case 1: return(WebSocketState.Open); case 2: return(WebSocketState.Closing); case 3: return(WebSocketState.Closed); default: return(WebSocketState.Closed); } }
/// <summary> /// Open WebSocket connection /// </summary> public void Connect() { int ret = WebSocketConnect(this.instanceId); if (ret < 0) { throw WebSocketHelpers.GetErrorMessageFromCode(ret, null); } }
/// <summary> /// Close WebSocket connection with optional status code and reason. /// </summary> /// <param name="code">Close status code.</param> /// <param name="reason">Reason string.</param> public Task Close(WebSocketCloseCode code = WebSocketCloseCode.Normal, string reason = null) { int ret = WebSocketClose(this.instanceId, (int)code, reason); if (ret < 0) { throw WebSocketHelpers.GetErrorMessageFromCode(ret, null); } return(Task.CompletedTask); }
/// <summary> /// Send binary data over the socket. /// </summary> /// <param name="data">Payload data.</param> public Task Send(byte[] bytes, int offset, int length) { //TODO: Handle offset and pointer passing. int ret = WebSocketSend(this.instanceId, bytes, length); if (ret < 0) { throw WebSocketHelpers.GetErrorMessageFromCode(ret, null); } return(Task.CompletedTask); }
public async Task Receive() { lock (SyncObj) { //Websocket only allows one receive call at a time. if (isReading) { return; } isReading = true; } try { WebSocketReceiveResult result = await m_Socket.ReceiveAsync(new ArraySegment <byte>(InternalBuffer), CancellationToken.None); if (result == null) { return; } if (result.MessageType == WebSocketMessageType.Binary) { lock (SyncObj) { OnMessage?.Invoke(new ArraySegment <byte>(InternalBuffer, 0, result.Count)); } } else if (result.MessageType == WebSocketMessageType.Close) { await Close(); OnClose?.Invoke(WebSocketHelpers.ParseCloseCodeEnum((int)result.CloseStatus)); } } catch (Exception e) { Console.WriteLine($"{nameof(DefaultWebSocketClient)} failed to receive message. Reason: {e}"); throw; } finally { isReading = false; } }
/// <summary> /// Delegate onClose event from JSLIB to native sharp event /// Is called by WebSocketFactory /// </summary> /// <param name="closeCode">Close status code.</param> public void DelegateOnCloseEvent(int closeCode) { this.OnClose?.Invoke(WebSocketHelpers.ParseCloseCodeEnum(closeCode)); }