コード例 #1
0
ファイル: JsonRpcClient.cs プロジェクト: psollberger/DeriSock
        /// <inheritdoc />
        public virtual async Task Connect()
        {
            if (Socket != null)
            {
                throw new JsonRpcAlreadyConnectedException();
            }

            Socket?.Dispose();
            RequestMgr.Reset();

            ReceiveCancellationTokenSource = new CancellationTokenSource();

            if (Logger?.IsEnabled(LogEventLevel.Information) ?? false)
            {
                Logger.Information("Connecting to {Host}", ServerUri);
            }

            Socket = WebSocketFactory.Create();
            try
            {
                await Socket.ConnectAsync(ServerUri, CancellationToken.None).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger?.Error(ex, "Exception during ConnectAsync");
                Socket.Dispose();
                Socket = null;
                throw;
            }

            InternalOnConnected();
        }
コード例 #2
0
        protected void ConnectWebSocket()
        {
            if (string.IsNullOrEmpty(FTLSocketUri))
            {
                Debug.LogError("FTL SocketUri must be set");
                return;
            }

            var customHeaders = new List <KeyValuePair <string, string> >();

            if (Headers != null)
            {
                foreach (UnityKeyValue header in Headers)
                {
                    customHeaders.Add(new KeyValuePair <string, string>(header.key, header.value));
                }
            }

#if ENABLE_WINMD_SUPPORT
            Debug.Log("Using UWP Web Socket");
            _ws = new WebSocketUWP();
#elif UNITY_EDITOR || ENABLE_MONO
            Debug.Log("Using Mono FTL Socket");
            _ws = new WebSocketMono();
#endif

            if (!isAttached)
            {
                _ws.ConfigureWebSocket(FTLSocketUri, customHeaders);
                Debug.Log("Connect FTL Socket: " + _ws.Url());
                AttachHandlers();
                _ws.ConnectAsync();
            }
        }
コード例 #3
0
        // testing/mocking
        protected virtual async Task OpenWebSocket(IWebSocket webSocket, Uri uri)
        {
            CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_disconnectTokenSource.Token, _disconnectToken);
            CancellationToken       token     = linkedCts.Token;
            await webSocket.ConnectAsync(uri, token);

            await Task.Delay(ReconnectDelay);
        }
コード例 #4
0
        internal static IWebSocket CreateWebSocketThatConnectsSuccessful()
        {
            IWebSocket webSocket = A.Fake <IWebSocket>();

            A.CallTo(() => webSocket.ConnectAsync()).Invokes(() =>
            {
                webSocket.OnOpen += Raise.With(webSocket, EventArgs.Empty);
            });
            return(webSocket);
        }
コード例 #5
0
        internal static IWebSocket CreateWebSocketThatFailsConnectDueTimeout(ITimer timer)
        {
            IWebSocket webSocket = A.Fake <IWebSocket>();

            A.CallTo(() => webSocket.ConnectAsync()).Invokes(() =>
            {
                timer.Elapsed += Raise.With <ElapsedEventHandler>(timer, new EventArgs() as ElapsedEventArgs);
            });
            return(webSocket);
        }
コード例 #6
0
        public void TestConnectCallsWebSocketConnectAsync()
        {
            WebSocketJetConnection webSocketJetConnection = new WebSocketJetConnection("ws://172.19.191.179:8081");
            ITimer timer = A.Dummy <ITimer>();

            webSocketJetConnection.ConnectTimer = timer;
            IWebSocket webSocket = A.Fake <IWebSocket>();

            webSocketJetConnection.SetWebSocket(webSocket);

            webSocketJetConnection.Connect(A.Dummy <Action <bool> >(), 1000.0);
            A.CallTo(() => webSocket.ConnectAsync()).MustHaveHappened(Repeated.Exactly.Once);
        }
コード例 #7
0
        /// <summary>
        /// Connect to the websocket server.
        /// </summary>
        /// <param name="cancellationToken"></param>
        public async Task ConnectAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                logger?.LogInformation("Trying to connect to '{uri}'", uri);

                await webSocket.ConnectAsync(new Uri(uri), cancellationToken);

                InvokeConnected();
                _ = Task.Run(() => StartListening());
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "Error while connecting to '{uri}'", uri);
                throw;
            }
        }
コード例 #8
0
        /// <summary>
        /// The socket send pump.
        /// </summary>
        /// <param name="socket">
        /// The socket.
        /// </param>
        /// <param name="uri">
        /// The uri.
        /// </param>
        /// <param name="cancellation">
        /// The cancellation.
        /// </param>
        /// <returns>
        /// The observer used to send messages to the socket.
        /// </returns>
        private static Func <string, Task> SocketSendPump(IWebSocket socket, Uri uri, CancellationTokenSource cancellation, TaskCompletionSource <int> connected)
        {
            var sender = new MutuallyExclusiveTaskExecutor();

            sender.Schedule(
                async() =>
            {
                try
                {
                    await socket.ConnectAsync(uri).AsTask(cancellation.Token).ConfigureAwait(false);
                    connected.TrySetResult(0);
                }
                catch
                {
                    cancellation.Cancel();
                }
            });

            var writer = new DataWriter(socket.OutputStream);

            sender.Run(cancellation.Token).ContinueWith(
                _ =>
            {
                if (_.Status != TaskStatus.RanToCompletion)
                {
                    cancellation.Cancel();
                }

                sender.Dispose();
            },
                CancellationToken.None);
            return(next => sender.Schedule(
                       async() =>
            {
                try
                {
                    writer.WriteString(next);
                    await writer.StoreAsync().AsTask(cancellation.Token).ConfigureAwait(false);
                }
                catch
                {
                    cancellation.Cancel();
                }
            }));
        }
コード例 #9
0
        /// <summary>
        /// Connect to the websocket server.
        /// </summary>
        /// <param name="cancellationToken"></param>
        public async Task ConnectAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                logger?.LogInformation("Trying to connect to '{uri}'", uri);

                await webSocket.ConnectAsync(new Uri(uri), cancellationToken);

                InvokeConnected();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                StartListening();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "Error while connecting to '{uri}'", uri);
                throw;
            }
        }
コード例 #10
0
    private void OnGUI()
    {
        var scale = Screen.width / 800f;

        GUI.matrix = Matrix4x4.TRS(new Vector3(0, 0, 0), Quaternion.identity, new Vector3(scale, scale, 1));
        var width = GUILayout.Width(Screen.width / scale - 10);

        WebSocketState state = socket == null ? WebSocketState.Closed : socket.ReadyState;

        GUILayout.Label("SDK Version: 2.5.0", width);
        var stateColor = state == WebSocketState.Closed ? "red" : state == WebSocketState.Open ? "#11ff11" : "#aa4444";
        var richText   = new GUIStyle()
        {
            richText = true
        };

        GUILayout.Label(string.Format(" <color=white>State:</color> <color={1}>{0}</color>", state, stateColor), richText);

        GUI.enabled = state == WebSocketState.Closed;
        GUILayout.Label("Address: ", width);
        address = GUILayout.TextField(address, width);

        GUILayout.BeginHorizontal();
        GUI.enabled = state == WebSocketState.Closed;
        if (GUILayout.Button(state == WebSocketState.Connecting ? "Connecting..." : "Connect"))
        {
            socket            = new WebSocket(address);
            socket.OnOpen    += Socket_OnOpen;
            socket.OnMessage += Socket_OnMessage;
            socket.OnClose   += Socket_OnClose;
            socket.OnError   += Socket_OnError;
            AddLog(string.Format("Connecting...\n"));
            socket.ConnectAsync();
        }

        GUI.enabled = state == WebSocketState.Open;
        if (GUILayout.Button(state == WebSocketState.Closing ? "Closing..." : "Close"))
        {
            AddLog(string.Format("Closing...\n"));
            socket.CloseAsync();
        }
        GUILayout.EndHorizontal();

        GUILayout.Label("Text: ");
        sendText = GUILayout.TextArea(sendText, GUILayout.MinHeight(50), width);

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Send"))
        {
            if (!string.IsNullOrEmpty(sendText))
            {
                socket.SendAsync(sendText);
                if (logMessage)
                {
                    AddLog(string.Format("Send: {0}\n", sendText));
                }
                sendCount += 1;
            }
        }
        if (GUILayout.Button("Send Bytes"))
        {
            if (!string.IsNullOrEmpty(sendText))
            {
                var bytes = System.Text.Encoding.UTF8.GetBytes(sendText);
                socket.SendAsync(bytes);

                if (logMessage)
                {
                    AddLog(string.Format("Send Bytes ({1}): {0}\n", sendText, bytes.Length));
                }
                sendCount += 1;
            }
        }
        if (GUILayout.Button("Send x100"))
        {
            if (!string.IsNullOrEmpty(sendText))
            {
                for (int i = 0; i < 100; i++)
                {
                    var text = (i + 1).ToString() + ". " + sendText;
                    socket.SendAsync(text);

                    if (logMessage)
                    {
                        AddLog(string.Format("Send: {0}\n", text));
                    }
                    sendCount += 1;
                }
            }
        }
        if (GUILayout.Button("Send Bytes x100"))
        {
            if (!string.IsNullOrEmpty(sendText))
            {
                for (int i = 0; i < 100; i++)
                {
                    var text  = (i + 1).ToString() + ". " + sendText;
                    var bytes = System.Text.Encoding.UTF8.GetBytes(text);
                    socket.SendAsync(bytes);
                    if (logMessage)
                    {
                        AddLog(string.Format("Send Bytes ({1}): {0}\n", text, bytes.Length));
                    }
                    sendCount += 1;
                }
            }
        }
        GUILayout.EndHorizontal();

        GUI.enabled = true;
        GUILayout.BeginHorizontal();
        logMessage = GUILayout.Toggle(logMessage, "Log Message");
        GUILayout.Label(string.Format("Send Count: {0}", sendCount));
        GUILayout.Label(string.Format("Receive Count: {0}", receiveCount));
        GUILayout.EndHorizontal();

        if (GUILayout.Button("Clear"))
        {
            log          = "";
            receiveCount = 0;
            sendCount    = 0;
        }

        scrollPos = GUILayout.BeginScrollView(scrollPos, GUILayout.MaxHeight(Screen.height / scale - 270), width);
        GUILayout.Label(log);
        GUILayout.EndScrollView();
    }
コード例 #11
0
ファイル: WebSocketTransport.cs プロジェクト: kietnha/SignalR
 // testing/mocking
 protected virtual async Task OpenWebSocket(IWebSocket webSocket, Uri uri)
 {
     await webSocket.ConnectAsync(uri);
 }
コード例 #12
0
 public void ConnectAsync()
 {
     _rawSocket.ConnectAsync();
 }
コード例 #13
0
ファイル: WebSocket.cs プロジェクト: wuhuolong/UnityWebSocket
 public void ConnectAsync(string address)
 {
     _rawSocket.ConnectAsync(address);
 }
コード例 #14
0
 // testing/mocking
 protected virtual async Task OpenWebSocket(IWebSocket webSocket, Uri uri)
 {
     await webSocket.ConnectAsync(uri);
 }
コード例 #15
0
        private void OnGUI()
        {
            var scale = Screen.width / 800f;

            GUI.matrix = Matrix4x4.TRS(new Vector3(0, 0, 0), Quaternion.identity, new Vector3(scale, scale, 1));
            var width = GUILayout.Width(Screen.width / scale - 10);

            WebSocketState state = socket == null ? WebSocketState.Closed : socket.ReadyState;

            GUILayout.BeginHorizontal();
            GUILayout.Label("SDK Version: " + Settings.VERSION, GUILayout.Width(Screen.width / scale - 100));
            GUI.color = green;
            GUILayout.Label($"FPS: {fps:F2}", GUILayout.Width(80));
            GUI.color = Color.white;
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("State: ", GUILayout.Width(36));
            GUI.color = WebSocketState.Closed == state ? red : WebSocketState.Open == state ? green : wait;
            GUILayout.Label($"{state}", GUILayout.Width(120));
            GUI.color = Color.white;
            GUILayout.EndHorizontal();

            GUI.enabled = state == WebSocketState.Closed;
            GUILayout.Label("Address: ", width);
            address = GUILayout.TextField(address, width);

            GUILayout.BeginHorizontal();
            GUI.enabled = state == WebSocketState.Closed;
            if (GUILayout.Button(state == WebSocketState.Connecting ? "Connecting..." : "Connect"))
            {
                socket            = new WebSocket(address);
                socket.OnOpen    += Socket_OnOpen;
                socket.OnMessage += Socket_OnMessage;
                socket.OnClose   += Socket_OnClose;
                socket.OnError   += Socket_OnError;
                AddLog(string.Format("Connecting..."));
                socket.ConnectAsync();
            }

            GUI.enabled = state == WebSocketState.Open;
            if (GUILayout.Button(state == WebSocketState.Closing ? "Closing..." : "Close"))
            {
                AddLog(string.Format("Closing..."));
                socket.CloseAsync();
            }
            GUILayout.EndHorizontal();

            GUILayout.Label("Message: ");
            sendText = GUILayout.TextArea(sendText, GUILayout.MinHeight(50), width);

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Send") && !string.IsNullOrEmpty(sendText))
            {
                socket.SendAsync(sendText);
                AddLog(string.Format("Send: {0}", sendText));
                sendCount += 1;
            }
            if (GUILayout.Button("Send Bytes") && !string.IsNullOrEmpty(sendText))
            {
                var bytes = System.Text.Encoding.UTF8.GetBytes(sendText);
                socket.SendAsync(bytes);
                AddLog(string.Format("Send Bytes ({1}): {0}", sendText, bytes.Length));
                sendCount += 1;
            }
            if (GUILayout.Button("Send x100") && !string.IsNullOrEmpty(sendText))
            {
                for (int i = 0; i < 100; i++)
                {
                    var text = (i + 1).ToString() + ". " + sendText;
                    socket.SendAsync(text);
                    AddLog(string.Format("Send: {0}", text));
                    sendCount += 1;
                }
            }
            if (GUILayout.Button("Send Bytes x100") && !string.IsNullOrEmpty(sendText))
            {
                for (int i = 0; i < 100; i++)
                {
                    var text  = (i + 1).ToString() + ". " + sendText;
                    var bytes = System.Text.Encoding.UTF8.GetBytes(text);
                    socket.SendAsync(bytes);
                    AddLog(string.Format("Send Bytes ({1}): {0}", text, bytes.Length));
                    sendCount += 1;
                }
            }

            GUILayout.EndHorizontal();

            GUI.enabled = true;
            GUILayout.BeginHorizontal();
            logMessage = GUILayout.Toggle(logMessage, "Log Message");
            GUILayout.Label(string.Format("Send Count: {0}", sendCount));
            GUILayout.Label(string.Format("Receive Count: {0}", receiveCount));
            GUILayout.EndHorizontal();

            if (GUILayout.Button("Clear"))
            {
                log          = "";
                receiveCount = 0;
                sendCount    = 0;
            }

            scrollPos = GUILayout.BeginScrollView(scrollPos, GUILayout.MaxHeight(Screen.height / scale - 270), width);
            GUILayout.Label(log);
            GUILayout.EndScrollView();
        }
コード例 #16
0
 public void ConnectAsync()
 {
     connection.OnOpen += Connection_OnOpen;
     connection.ConnectAsync();
 }