ConnectAsync() публичный Метод

Establishes a WebSocket connection asynchronously.

This method does not wait for the connect to be complete.

This method is not available in a server.

public ConnectAsync ( ) : void
Результат void
Пример #1
0
        public IEnumerator Connect(GamebaseCallback.ErrorDelegate callback)
        {
            CreateSocket();

            socket.ConnectAsync();

            float waitTime = 0;

            while (false == IsConnected() && null == GetErrorMessage() && waitTime < CommunicatorConfiguration.connectionTimeout)
            {
                waitTime += Time.unscaledDeltaTime;
                yield return(null);
            }

            GamebaseError error = null;

            if (false == string.IsNullOrEmpty(GetErrorMessage()))
            {
                error = new GamebaseError(GamebaseErrorCode.SOCKET_ERROR, message: GetErrorMessage());
            }
            else
            {
                if (waitTime >= CommunicatorConfiguration.connectionTimeout)
                {
                    error = new GamebaseError(GamebaseErrorCode.SOCKET_ERROR);
                }
            }

            StartRecvPolling();

            callback(error);
        }
Пример #2
0
 public IEnumerator Connect()
 {
     m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString());
     m_Socket.OnMessage += (sender, e) =>
     {
         m_Messages.Enqueue(e.RawData);
     };
     m_Socket.OnOpen += (sender, e) =>
     {
         m_IsConnected = true;
         isConnected   = true;
     };
     m_Socket.OnError += (sender, e) =>
     {
         m_Error = e.Message;
         if (OnError != null)
         {
             OnError.Invoke(this, new ErrorEventArgs(m_Error));
         }
     };
     m_Socket.ConnectAsync();
     while (!m_IsConnected && m_Error == null)
     {
         yield return(0);
     }
     if (OnOpen != null)
     {
         OnOpen.Invoke(this, new EventArgs());
     }
 }
Пример #3
0
    /// <summary>
    /// Attempts to create a web socket connected to <paramref name="url"/>, returning the socket
    /// once the connection was successfully establish. Throws an exception if the connection
    /// fails.
    /// </summary>
    ///
    /// <param name="url">The endpoint to connect to.</param>
    ///
    /// <returns>The web socket once the connection has been established.</returns>
    ///
    /// <exception cref="WebSocketException">
    /// Throws an exception if the connection fails or if an error occurs before the connection
    /// can be established.
    /// </exception>
    public static Task <WebSocket> ConnectAsync(Uri url)
    {
        var protocol = url.Scheme;

        if (protocol != "ws" && protocol != "wss")
        {
            throw new ArgumentException("Unsupported protocol: " + protocol);
        }

        // Create a completion source so that we can return the finished web socket
        // asynchronously.
        var completion = new TaskCompletionSource <WebSocket>();

        // Create the underlying socket and setup callbacks to either yield the connected
        // WebSocket or return an error if the connection fails.
        var socket = new WebSocketSharp.WebSocket(url.ToString());

        socket.OnOpen += (sender, e) =>
        {
            completion.TrySetResult(new WebSocket(url, socket));
        };
        socket.OnError += (sender, args) =>
        {
            completion.TrySetException(new WebSocketException(args.Message));
        };

        // Begin the connection and return the task.
        socket.ConnectAsync();
        return(completion.Task);
    }
Пример #4
0
    public IEnumerator Connect()
    {
        m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString());
        m_Socket.OnMessage += (sender, e) => { m_Messages.Enqueue(e.RawData); };
        m_Socket.OnOpen    += (sender, e) => { m_IsConnected = true; };
        m_Socket.OnError   += (sender, e) => { Debug.LogError(">>>>> OnError " + e.Message); m_Error = e.Message; };
        m_Socket.OnClose   += (sender, e) => { m_IsConnected = false; };

/*
 *              m_Socket.Log = new WebSocketSharp.Logger( WebSocketSharp.LogLevel.Trace, null, (WebSocketSharp.LogData data, string str)=>{
 *                      switch( data.Level){
 *                              case WebSocketSharp.LogLevel.Trace:
 *                              case WebSocketSharp.LogLevel.Debug:
 *                              Debug.Log("WebSocketSharp "+data.Message);
 *                              break;
 *                              case WebSocketSharp.LogLevel.Info:
 *                              case WebSocketSharp.LogLevel.Warn:
 *                              Debug.LogWarning("WebSocketSharp "+data.Message);
 *                              break;
 *                              case WebSocketSharp.LogLevel.Error:
 *                              case WebSocketSharp.LogLevel.Fatal:
 *                              Debug.LogError("WebSocketSharp "+data.Message);
 *                              break;
 *                      }
 *              } );
 */
        m_Socket.ConnectAsync();
        while (!m_IsConnected && m_Error == null)
        {
            yield return(0);
        }
    }
Пример #5
0
    public IEnumerator Connect()
    {
        m_Socket = new WebSocketSharp.WebSocket(m_url);

        m_Socket.OnMessage += (sender, e) =>
        {
            m_Messages.Enqueue(e.RawData);
        };

        m_Socket.OnOpen += (sender, e) =>
        {
            m_IsConnected = true;
        };

        m_Socket.OnError += (sender, e) =>
        {
            m_Error = e.Message;
        };

        m_Socket.OnClose += (sender, e) =>
        {
            m_Error = e.Reason;
        };

        m_Socket.ConnectAsync();

        while (!m_IsConnected && m_Error == null)
        {
            yield return(new WaitForEndOfFrame());
        }
    }
Пример #6
0
    public IEnumerator Connect()
    {
        if (m_Socket == null)
        {
            m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString());
            m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
            m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
            m_Socket.OnClose   += (sender, e) => { m_IsConnected = false; if (OnClosed != null)
                                                   {
                                                       OnClosed(sender, e);
                                                   }
            };
            m_Socket.OnError += (sender, e) => { m_Error = e.Message; if (OnError != null)
                                                 {
                                                     OnError(sender, e);
                                                 }
            };
        }

        m_Socket.ConnectAsync();
        while (!m_IsConnected && m_Error == null)
        {
            yield return(0);
        }
    }
Пример #7
0
        public bool Connnet()
        {
            try
            {
                websocket = new WebSocketSharp.WebSocket(WEBSOCKET_API);

                websocket.OnError += (sender, e) =>
                {
                    Console.WriteLine("Error:" + e.Exception.Message.ToString());
                    Log4NetUtility.Debug("OnError", e.Exception.Message);
                };
                websocket.OnOpen    += OnOpened;
                websocket.OnClose   += Websocket_Closed;;
                websocket.OnMessage += ReceviedMsg;
                websocket.ConnectAsync();
                while (!websocket.IsAlive)
                {
                    Console.WriteLine("Waiting WebSocket connnet......");
                    Thread.Sleep(1000);
                }
                heartBeatTimer.Elapsed += new System.Timers.ElapsedEventHandler(heatBeat);
                //heartBeatTimer.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception:" + ex.Message);
                Log4NetUtility.Error("WebSocketApi_OK", Utils.Exception2String(ex));
            }
            return(true);
        }
Пример #8
0
        public static void ConnectAsync(this WebSocket socket, Action OnConnect, Action <Exception> OnError)
        {
            Action onDone = () => { };

            EventHandler onConnect = (sender, e) => {
                if (OnConnect != null)
                {
                    OnConnect();
                }
                onDone();
            };

            EventHandler <CloseEventArgs> onClose = (sender, e) => {
                if (OnError != null)
                {
                    OnError(new Exception(e.Reason));
                }
                onDone();
            };

            onDone = () => {
                socket.OnOpen  -= onConnect;
                socket.OnClose -= onClose;
            };

            socket.OnOpen  += onConnect;
            socket.OnClose += onClose;

            socket.ConnectAsync();
        }
Пример #9
0
        public NetworkInterface(string address, ContentManager c)
        {

            sock = new WebSocket(address);
            Content = c;
            connected = false;
            sock.OnMessage += (sender, e) =>
            {
                byte[] r = e.RawData;
                string s = System.Text.Encoding.UTF8.GetString(r);
                doNetworkInput(s);
            };
            sock.OnOpen += (sender, e) =>
            {
                connected = true;
                Console.WriteLine("Connected");
                onReady();
            };
            sock.OnClose += (sender, e) =>
            {
                Console.WriteLine("Ran onclose");
                connected = false;
            };
            sock.OnError += (sender, e) =>
            {
                if (e.Message == "An error has occurred while connecting.")
                {
                    connected = false;
                    onReady();
                }
            };
            sock.ConnectAsync();
        }
Пример #10
0
    void Start() {
        ws = new WebSocket("ws://echo.websocket.org");

        ws.OnOpen += OnOpenHandler;
        ws.OnMessage += OnMessageHandler;
        ws.OnClose += OnCloseHandler;

        stateMachine.AddHandler(State.Running, () => {
            new Wait(this, 3, () => {
                ws.ConnectAsync();
            });
        });

        stateMachine.AddHandler(State.Connected, () => {
            stateMachine.Transition(State.Ping);
        });

        stateMachine.AddHandler(State.Ping, () => {
            new Wait(this, 3, () => {
               ws.SendAsync("This WebSockets stuff is a breeze!", OnSendComplete);
            });
        });

        stateMachine.AddHandler(State.Pong, () => {
            new Wait(this, 3, () => {
                ws.CloseAsync();
            });
        });

        stateMachine.Run();
    }
Пример #11
0
 public void Connect()
 {
     m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString());
     m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
     m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
     m_Socket.OnError   += (sender, e) => m_Error = e.Message;
     m_Socket.ConnectAsync();
 }
Пример #12
0
 public void Connect()
 {
     socket = new WebSocketSharp.WebSocket(mUrl.ToString(), new string[] { this.protocols });
     socket.SslConfiguration.EnabledSslProtocols = socket.SslConfiguration.EnabledSslProtocols | (SslProtocols)(3072 | 768);
     socket.OnMessage += (sender, e) => messages.Enqueue(e.RawData);
     socket.OnOpen    += (sender, e) => isConnected = true;
     socket.OnError   += (sender, e) => error = e.Message + (e.Exception == null ? "" : " / " + e.Exception);
     socket.ConnectAsync();
 }
Пример #13
0
 public void Connect()
 {
     m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString(), new string[] { "GpBinaryV16" });// modified by TS
     // m_Socket.SslConfiguration.EnabledSslProtocols = m_Socket.SslConfiguration.EnabledSslProtocols | (SslProtocols)(3072| 768);
     m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
     m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
     m_Socket.OnError   += (sender, e) => m_Error = e.Message + (e.Exception == null ? "" : " / " + e.Exception);
     m_Socket.ConnectAsync();
 }
Пример #14
0
    void Start() {
        ws = new WebSocket("ws://echo.websocket.org");

        ws.OnOpen += OnOpenHandler;
        ws.OnMessage += OnMessageHandler;
        ws.OnClose += OnCloseHandler;

        ws.ConnectAsync();        
    }
Пример #15
0
 private void ResetSocket()
 {
     websocket            = new WebSocketSharp.WebSocket(FC_WEBSOCKET_API);
     websocket.OnError   += Websocket_OnError;
     websocket.OnOpen    += OnOpened;
     websocket.OnClose   += Websocket_Closed;
     websocket.OnMessage += ReceviedMsg;
     websocket.ConnectAsync();
     Console.WriteLine("SetSocket !");
 }
Пример #16
0
        public static IPromise ConnectPromise(this WebSocket socket)
        {
            var promise = new Promise();

            socket.ConnectAsync(
                () => promise.Resolve(),
                exception => promise.Reject(exception)
                );
            return(promise);
        }
Пример #17
0
    // Use this for initialization
    void Start()
    {
        ws = new WebSocket(serverIp);

        ws.OnOpen += OnOpenHandler;
        ws.OnMessage += OnMessageHandler;
        ws.OnClose += OnCloseHandler;

        ws.ConnectAsync();
    }
Пример #18
0
    public void Connect()
    {
        m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString(), new string[] { "GpBinaryV16" });// modified by TS

        m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
        m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
        m_Socket.OnError   += (sender, e) => m_Error = e.Message + (e.Exception == null ? "" : " / " + e.Exception);
        m_Socket.ConnectAsync();
        //while (!m_IsConnected && m_Error == null)
        //    yield return 0;
    }
Пример #19
0
        /// <summary>
        /// Creates a <see cref="T:OctoprintClient.OctoprintConnection"/>
        /// </summary>
        /// <param name="eP">The endpoint Address like "http://192.168.1.2/"</param>
        /// <param name="aK">The Api Key of the User account you want to use. You can get this in the user settings</param>

        public OctoprintConnectionUWP(string eP, string aK) : base(eP, aK)
        {
            Position = new OctoprintPos(this);
            Files    = new OctoprintFileTracker(this);
            Jobs     = new OctoprintJobTracker(this);
            Printer  = new OctoprintPrinter(this);

            WebSocket = new WebSocket(GetWebsocketurl());
            WebSocket.ConnectAsync();
            WebSocket.OnMessage += webSocket_OnMessage;
        }
Пример #20
0
 void Start()
 {
     Adress             += Ip + ":" + Port;
     m_Socket            = new WebSocketSharp.WebSocket(Adress);
     m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
     m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
     m_Socket.OnClose   += (sender, e) => m_IsConnected = false;
     m_Socket.OnError   += (sender, e) => m_Error = e.Message;
     m_Socket.ConnectAsync();
     Debug.Log("Init WebSocket");
     m_Socket.Connect();
 }
Пример #21
0
 public IEnumerator Connect()
 {
     m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString(), "eqemu");
     m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
     m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
     m_Socket.OnError   += (sender, e) => m_Error = e.Message;
     m_Socket.ConnectAsync();
     while (!m_IsConnected && m_Error == null)
     {
         yield return(0);
     }
 }
Пример #22
0
 public void Connect()
 {
     m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString(), new string[] { this.protocols });
     m_Socket.SslConfiguration.EnabledSslProtocols = m_Socket.SslConfiguration.EnabledSslProtocols | (SslProtocols)(3072 | 768);
     m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
     m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
     //this.m_Socket.Log.Level = LogLevel.Debug;
     //this.m_Socket.Log.Output += Output;
     this.m_Socket.OnClose += SocketOnClose;
     m_Socket.OnError      += (sender, e) => m_Error = e.Message + (e.Exception == null ? "" : " / " + e.Exception);
     m_Socket.ConnectAsync();
 }
Пример #23
0
        public void get()
        {
            string host = "ws://reqres.in/api/users";

            WebSocketSharp.WebSocket soc;
            soc = new WebSocketSharp.WebSocket(host);
            soc.ConnectAsync();
            soc.OnMessage += (sender, e) =>
            {
                var d = e.Data;
            };
        }
Пример #24
0
 public IEnumerator Connect()
 {
     m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString());
     m_Socket.OnMessage += OnMessage;
     m_Socket.OnOpen    += OnOpen;
     m_Socket.OnError   += OnError;
     m_Socket.OnClose   += OnClose;
     m_Socket.ConnectAsync();
     while (!m_IsConnected && m_Error == null)
     {
         yield return(0);
     }
 }
Пример #25
0
 public IEnumerator Connect()
 {
     m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString());
     m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
     m_Socket.OnOpen    += stuffonopen;
     m_Socket.OnError   += stuffonerror;
     m_Socket.OnClose   += stuffonclose;
     m_Socket.ConnectAsync();
     while (!m_IsConnected && m_Error == null)
     {
         yield return(0);
     }
 }
Пример #26
0
 private void Websocket_Closed(object sender, EventArgs e)
 {
     heartBeatTimer.Close();
     Console.WriteLine($"Websocket_Closed");
     OnClosed?.Invoke(null, null);
     websocket.ConnectAsync();
     countConnect++;
     while (!websocket.IsAlive)
     {
         Console.WriteLine("Waiting WebSocket connnet......");
         Thread.Sleep(1000);
     }
 }
Пример #27
0
 public void start() {
     webSocketClient = new WebSocket(url);
     webSocketClient.OnError += new EventHandler<WebSocketSharp.ErrorEventArgs>(webSocketClient_Error);
     webSocketClient.OnOpen += new EventHandler(webSocketClient_Opened);
     webSocketClient.OnClose += new EventHandler<WebSocketSharp.CloseEventArgs>(webSocketClient_Closed);
     webSocketClient.OnMessage += new EventHandler<MessageEventArgs>(webSocketClient_MessageReceived);
     webSocketClient.ConnectAsync();
     while (!webSocketClient.IsAlive) {
         Console.WriteLine("Waiting WebSocket connnet......");
         Thread.Sleep(1000);
     }
     t.Elapsed += new System.Timers.ElapsedEventHandler(heatBeat);
     t.Start();
 }
Пример #28
0
    void StartWebSocket()
    {
        Debug.Log("[Client] Connecting...");

        float timeConnection = Time.time;

        w = new WebSocketSharp.WebSocket(url);

        w.OnMessage += (sender, e) => OnMessage(e);
        w.OnOpen    += (sender, e) => OnOpen();
        w.OnError   += (sender, e) => OnError(e);
        w.OnClose   += (sender, e) => OnClose(e);
        w.ConnectAsync();
    }
Пример #29
0
	void Start () {

		// Retrieve the main camera
		mainCam = Camera.main; 

		// Create and Open the websocket
		ws = new WebSocket("ws://"+ GatewayIP + ":" + WebsocketPort);
		ws.OnOpen += OnOpenHandler;
		ws.OnMessage += OnMessageHandler;
		ws.OnClose += OnCloseHandler;

		ws.ConnectAsync();

	}
Пример #30
0
 public IEnumerator ConnectWebsocket()
 {
     //maybe need to add some code here to check protocol of URI to make sure
     // it is "ws" or "wss". Not sure what happens when you throw an exception
     // in a monobehavior function.
     w            = new WebSocketSharp.WebSocket(address.ToString());
     w.OnMessage += gotMessage;
     w.OnOpen    += (sender, e) => socketIsConnected = true;
     w.OnError   += (sender, e) => socketError = e.Message;
     w.ConnectAsync();
     while (!socketIsConnected && socketError == null)
     {
         yield return(0);
     }
 }
        internal void Connect()
        {
            // TODO: Handle and test disconnection / errors etc
            // TODO: Add 'connecting_in' event

            ChangeState(ConnectionState.Connecting);
            _allowReconnect = true;

            _websocket = new WebSocket(_url);
            _websocket.OnError += websocket_Error;
            _websocket.OnOpen += websocket_Opened;
            _websocket.OnClose += websocket_Closed;
            _websocket.OnMessage += websocket_MessageReceived;
            _websocket.ConnectAsync();
        }
Пример #32
0
        public override object ConstructObject()
        {
            string[] protocols;
            if (FProtocols[this.CurrObj][0] != "")
            {
                protocols = new string[FProtocols[this.CurrObj].SliceCount];
                for (int i = 0; i < FProtocols[this.CurrObj].SliceCount; i++)
                {
                    protocols[i] = FProtocols[this.CurrObj][i];
                }
            }
            else
            {
                protocols = new string[0];
            }

            WebSocketSharp.WebSocket newWebSocket       = new WebSocketSharp.WebSocket(FUrl[this.CurrObj], protocols);
            VebSocketHostedClient    newVebSocketClient = new VebSocketHostedClient(newWebSocket);

            newVebSocketClient.SubscribeToMainloop(this.FHDEHost);

            if (FOrigin[this.CurrObj] != "")
            {
                newWebSocket.Origin = FOrigin[this.CurrObj];
            }

            if (FCookie.IsConnected && (FCookie[this.CurrObj] != null))
            {
                newWebSocket.SetCookie(FCookie[this.CurrObj]);
            }

            if (FServerCertValidCallback.IsConnected && (FServerCertValidCallback[this.CurrObj] != null))
            {
                newWebSocket.SslConfiguration.ServerCertificateValidationCallback = FServerCertValidCallback[this.CurrObj];
            }

            if ((FUser[this.CurrObj] != "") || (FPassword[this.CurrObj] != ""))
            {
                newWebSocket.SetCredentials(FUser[this.CurrObj], FPassword[this.CurrObj], FPreAuth[this.CurrObj]);
            }

            if (FAutoConnect[this.CurrObj])
            {
                newWebSocket.ConnectAsync();
            }

            return(newVebSocketClient);
        }
Пример #33
0
    public IEnumerator Connect()
    {
#endif
#if (UNITY_EDITOR || (!UNITY_WSA_10_0 && !UNITY_WEBGL))
        m_Error = null;
        m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString());
        m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
        m_Socket.OnOpen += (sender, e) => { m_IsConnected = true; m_Error = null; };
        m_Socket.OnClose += (sender, e) => { m_Error = "Closed"; Debug.Log("Closed!"); };
        m_Socket.OnError += (sender, e) => m_Error = e.Message;
        m_Socket.ConnectAsync();
        while (!m_IsConnected && m_Error == null)
        {
            yield return 0;
        }
    }
Пример #34
0
    public override void OnStartClient()
    {
        var setup = FindObjectOfType <GameFlow>().setup;

        _smoother = new Smoother <RawPoint>();  // original
        _smoother.saccadeThreshold = 30;        // 30
        _smoother.timeWindow       = 100;       // 150
        _smoother.dampFixation     = 250;       // 700

        _simulate = simulate || setup.mode == Setup.Mode.HeadGaze || (Environment.UserName == "csolsp" && Screen.currentResolution.width == 1920);

        if (_simulate)
        {
            _simulator         = FindObjectOfType <GazeSimulator>();
            _simulator.Sample += onSimulatorSample;
            _simulator.State  += onSimulatorState;
            _simulator.Device += onSimulatorDevice;
            _simulator.Initialize();
            return;
        }

        gazeControls.SetActive(true);

        _ws         = new WebSocketSharp.WebSocket("ws://localhost:8086/");
        _ws.OnOpen += (sender, e) =>
        {
            print("WS:> Connected");
        };
        _ws.OnClose += (sender, e) =>
        {
            print("WS:> Disconnected");
        };
        _ws.OnError += (sender, e) =>
        {
            print($"WS:> Error {e.Message}");
        };
        _ws.OnMessage += (sender, e) =>
        {
            //print($"WS:> MSG {e.Data}");
            lock (_messages)
            {
                _messages.Enqueue(e.Data);
            }
        };

        _ws.ConnectAsync();
    }
        private Task Init()
        {
            _openEvent.Reset();

            _webSocket = new WebSocketSharp.WebSocket(_endpoint);
            //_webSocket.EnableAutoSendPing = false;
            //_webSocket.Opened += WebSocket_Opened;
            //_webSocket.MessageReceived += WebSocket_MessageReceived;
            //_webSocket.Error += WebSocket_Error;
            //_webSocket.Closed += WebSocket_Closed;
            //_webSocket.DataReceived += WebSocket_DataReceived;
            //_webSocket.Open();

            _webSocket.OnOpen += (sender, e) => {
                _openEvent.Set();
            };

            _webSocket.OnError += (sender, e) => {
                throw e.Exception;
            };

            _webSocket.OnClose += (sender, e) => {
            };

            _webSocket.OnMessage += (sender, e) => {
                ICommandResponse response;
                if (TryGetCommandResponse(e.Data, out response))
                {
                    HandleResponse(response);
                    return;
                }
                IEvent evnt;
                if (TryGetEvent(e.Data, out evnt))
                {
                    HandleEvent(evnt);
                    return;
                }
                throw new Exception("Don't know what to do with response: " + e.Data);
            };

            _webSocket.ConnectAsync();

            return(Task.Run(() =>
            {
                _openEvent.WaitOne();
            }));
        }
Пример #36
0
    void Start()
    {
        toSend = new JSONClass();
        N = JSONNode.Parse("{\"op\": \"advertise\",\"topic\": \"helloString\",\"type\": \"std_msgs/String\"}");
        toSend["op"] = "publish";
        toSend["topic"] = "helloString";
        data = new JSONClass();
        data["data"] = "Why Hello there ros, Fancy meeting you here.";
        toSend["msg"] = data;
        ws = new WebSocket("ws://localhost:9090");

        ws.OnOpen += OnOpenHandler;
        ws.OnMessage += OnMessageHandler;
        ws.OnClose += OnCloseHandler;

        ws.ConnectAsync();
    }
Пример #37
0
    public IEnumerator Connect()
    {
        Debug.Log("WebSocket.Connect() non-WebGL: IN");
        m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString());
        m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
        m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
        m_Socket.OnError   += (sender, e) => m_Error = e.Message;
        m_Socket.ConnectAsync();
        Debug.Log("WebSocket.Connect() non-WebGL: after  ConnectAsync()");

        while (!m_IsConnected && m_Error == null)
        {
            //Debug.Log("WebSocket.Connect() non-WebGL: Connecting:");
            yield return(0);
        }

        Debug.Log("WebSocket.Connect() non-WebGL: Connected:" + m_IsConnected + " Error:" + m_Error + " m_Messages.size():" + m_Messages.Count);
    }
Пример #38
0
        public void Connect()
        {
            lock (_lock)
            {
                if (_isConnected == false)
                {
                    _isConnected = true;

                    _webSocket = new WebSocket(_bitMexWebSocketUrl);

                    _webSocket.OnOpen    += Websocket_OnOpen;
                    _webSocket.OnMessage += Websocket_OnMessage;
                    _webSocket.OnClose   += _webSocket_OnClose;
                    _webSocket.OnError   += _webSocket_OnError;

                    _webSocket.ConnectAsync();
                }
            }
        }
Пример #39
0
 public NetworkInterface(string address, ContentManager c)
 {
     Console.WriteLine("Hello");
     bufferedMap = new List<string>();
     bufferedPlayers = new List<string>();
     messagesReceived = 0;
     sock = new WebSocket(address);
     game = null;
     Content = c;
     connected = false;
     mapLoaded = false;
     roomNumber = -1;
     sock.OnMessage += (sender, e) =>
     {
         byte[] r = e.RawData;
         string s = System.Text.Encoding.UTF8.GetString(r);
         doNetworkInput(s);
     };
     sock.OnOpen += (sender, e) =>
     {
         connected = true;
         startTime = DateTime.Now;
         Console.WriteLine("Connected");
     };
     sock.OnClose += (sender, e) =>
     {
         Console.WriteLine("Ran onclose");
         connected = false;
         mapLoaded = false;
     };
     sock.OnError += (sender, e) =>
     {
         if (e.Message == "An error has occurred while connecting.")
         {
             connected = false;
             generateMap();
             onReady();
         }
     };
     sock.ConnectAsync();
 }
        public Task<bool> Connect()
        {
            var tcs = new TaskCompletionSource<bool>();

            _webSocket = new WebSocket("ws://127.0.0.1:{0}/debugger-proxy".ToFormat(Port));
            _webSocket.OnOpen += async (sender, args) =>
            {
                System.Diagnostics.Debug.WriteLine("WS: Opened");
                await PrepareJSRuntime();
                tcs.TrySetResult(true);
            };
            _webSocket.OnClose += (sender, args) =>
            {
                System.Diagnostics.Debug.WriteLine("WS: Closed");
            };
            _webSocket.OnMessage += (sender, args) =>
            {
                HandleJson(args.Data);
            };
            _webSocket.ConnectAsync();

            return tcs.Task;
        }
Пример #41
0
    void Start()
    {
        timeSinceLastObj = 0;
        resources = new List<ResourceObject>();
        prevPos = transform.position.x;
        prevScore = UIHandler.highestHeight;
        prevGrass = UIHandler.grassCount;
        prevWood = UIHandler.woodCount;
        prevRock = UIHandler.rockCount;
        spawnedResources = new List<GameObject>();

        ws = new WebSocket("ws://dvm.io:8081/socket.io/?EIO=3&transport=websocket");
        ws.OnError += (sender, e) => Debug.Log("ERROR: " + e.Message);
        ws.OnMessage += (sender, e) => onMessageReceived(sender,e);
        ws.ConnectAsync();
    }
Пример #42
0
	public IEnumerator Connect()
	{
		m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString());
        m_Socket.Log.Output += (logData, message) => { OnLogMessage(logData, message); };
		m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue (e.RawData);
		m_Socket.OnOpen += (sender, e) => m_IsConnected = true;
        m_Socket.OnError += (sender, e) => {
            m_Error = e.Message;
            OnError(e.Message);
        };
		m_Socket.ConnectAsync();
		while (!m_IsConnected && m_Error == null)
			yield return 0;
	}
Пример #43
0
 public void Connect(string host)
 {
     this.host = host;
     if(websocket != null)
     {
         Debug.LogWarning("Replacing existing websocket");
     }
     websocket = new WebSocket(host);
     websocket.Log.Output = this.LogDelegate;
     if (debugMode)
     {
         Debug.Log("Connecting to " + host);
         websocket.Log.Level = LogLevel.Trace;
     }
     websocket.OnOpen += this.Open;
     websocket.OnClose += this.Close;
     websocket.OnMessage += this.Message;
     websocket.OnError += this.Error;
     
     websocket.ConnectAsync();
 }
Пример #44
0
        private IEnumerator SocketConnect(SocketKey key)
        {
            var url = componentModel.getComponentWSURL(key.componentName);
            if (string.IsNullOrEmpty(url))
            {
                debug.LogError("Could not find url to open socket for component " + key.componentName, key);
                yield return null;
            }
            var ws = new WebSocket(url);
            sockets[key] = ws;

            ws.WaitTime = new TimeSpan(0, 0, 5);
            ws.OnMessage += (o, e) => onSocketMessage(key, o, e);
            ws.OnError += (o, e) => onSocketError(key, o, e);
            ws.OnOpen += (o, e) => onSocketOpen(key, o, e);
            ws.OnClose += (o, e) => onSocketClose(key, o, e);

            debug.Log("Attempting connection to " + url, key);
            ws.ConnectAsync();
            int i = 0;
            while (i < 1000)
            {
                i++;
                if (ws.ReadyState == WebSocketState.Open) break;
                yield return null;
            }
        }
        protected override void PreStart()
        {
            var self = Self;
            _socket = new WebSocket(_endpoint);
            _socket.OnOpen += (sender, args) =>
            {
                self.Tell(new ConnectionOpened());
            };

            _socket.OnMessage += (sender, args) =>
            {
                self.Tell(new MessageReceived(args));
            };

            _socket.OnError += (sender, args) =>
            {
                self.Tell(new ErrorOccurred(args.Message, args.Exception));
            };
            _socket.OnClose += (sender, args) =>
            {
                self.Tell(new ConnectionClosed());
            };

            _socket.SetCookie(new Cookie("ClientId", _clientId));
            _socket.ConnectAsync();
        }
Пример #46
0
 private void Connect() {
   if(_ws!=null) {
     if(_ws.IsAlive) {
       _ws.Close(CloseStatusCode.Normal);
     }
     _ws=null;
   }
   if(_st==State.BadAuth) {
     return;
   }
   if(_uri.IsDefaultPort) {
     _host=string.Concat(_uri.Scheme, "://", _uri.DnsSafeHost);
   } else {
     _host=string.Concat(_uri.Scheme, "://", _uri.DnsSafeHost, ":", _uri.Port.ToString());
   }
   _remotePath=_uri.AbsolutePath+_uri.Fragment;
   {
     int i;
     i=_remotePath.IndexOf("/#");
     if(i<0) {
       i=_remotePath.IndexOf("/+");
     }
     if(i>0) {
       _remoteBase=_remotePath.Substring(0, i);
     } else {
       _remoteBase=_remotePath;
     }
   }
   var up=Uri.UnescapeDataString(_uri.UserInfo).Split(':');
   _uName=up.Length>0?up[0]:string.Empty;
   _uPass=up.Length==2?up[1]:string.Empty;
   _ws=new WebSocket(_host+"/api/v03");
   _ws.Log.Output=WsLog;
   _ws.OnOpen+=_ws_OnOpen;
   _ws.OnMessage+=_ws_OnMessage;
   _ws.OnError+=_ws_OnError;
   _ws.OnClose+=_ws_OnClose;
   _ws.ConnectAsync();
   _reconn.Change(_rccnt * 15000, _rccnt * 30000);
 }
Пример #47
0
	public IEnumerator Connect()
	{
        m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString(), new string[] { "GpBinaryV16" });// modified by TS

		m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue (e.RawData);
		m_Socket.OnOpen += (sender, e) => m_IsConnected = true;
		m_Socket.OnError += (sender, e) => m_Error = e.Message + (e.Exception == null ? "" : " / "+ e.Exception);
		m_Socket.ConnectAsync();
		while (!m_IsConnected && m_Error == null)
			yield return 0;
	}
Пример #48
0
 private void Connect() {
   if(_ws != null) {
     if(_ws.IsAlive) {
       _ws.Close(CloseStatusCode.Normal);
     }
     _ws = null;
   }
   _ws = new WebSocket(_url);
   _ws.Log.Output = WsLog;
   _ws.OnOpen += _ws_OnOpen;
   _ws.OnMessage += _ws_OnMessage;
   _ws.OnError += _ws_OnError;
   _ws.OnClose += _ws_OnClose;
   _ws.ConnectAsync();
   _reconn.Change(_rccnt * 15000 - (DateTime.Now.Ticks & 0x1FFF), _rccnt * 30000);
 }
Пример #49
0
    void Start()
    {
        publishUnwrapped = false;
        Texture2D tex = new Texture2D(2, 2);
        string filepath = "ThermalPic.jpg";
        //if (System.IO.File.Exists(filepath))     {
        decodedBytes = System.IO.File.ReadAllBytes(filepath);
        tex.LoadImage(decodedBytes);
        ThermalImg.mainTexture = tex;
        ThermalImg2.mainTexture = tex;
        //definitions of subscriptions and advertisments to be sent to ros.
        N = JSONNode.Parse("{\"op\": \"subscribe\",\"topic\": \"thermalText\",\"type\": \"std_msgs/String\"}");
        triggerUnwrapped = JSONNode.Parse("{\"op\": \"subscribe\",\"topic\": \"triggerUnwrapped\",\"type\": \"std_msgs/String\"}");
        Unwrapped = JSONNode.Parse("{\"op\": \"advertise\",\"topic\": \"unwrappedImg\",\"type\": \"std_msgs/String\"}");
        chatter = JSONNode.Parse("{\"op\": \"advertise\",\"topic\": \"helloString\",\"type\": \"std_msgs/String\"}");

        toSend = new JSONClass();
        toSend["op"] = "publish";
        toSend["topic"] = "helloString";
        data = new JSONClass();
        data["data"] = "Why Hello there ros, Fancy meeting you here.";
        toSend["msg"] = data;
        ws = new WebSocket("ws://localhost:9090");

        Thread.Sleep(300);
        ws.OnOpen += OnOpenHandler;
        ws.OnMessage += OnMessageHandler;
        ws.OnClose += OnCloseHandler;

        ws.ConnectAsync();
    }
Пример #50
0
		public void ConnectWebSocket(string url)
		{
			Disconnect();

#if DEBUG
			Debug.Log("[SnipeClient] WebSocket Connect to " + url);
#endif

#if UNITY_WEBGL && !UNITY_EDITOR
			StartCoroutine(WebSocketConnect(url));
#else
			mWebSocket = new WebSocket(url);
			mWebSocket.OnOpen += OnWebSocketConnected;
			mWebSocket.OnClose += OnWebSocketClose;
			mWebSocket.OnError += OnWebSocketError;
			mWebSocket.OnMessage += OnWebSocketMessage;
			mWebSocket.ConnectAsync();
#endif
		}