public void OpenWebsocket(string connectionId, List <KeyValuePair <string, string> > websocketheaders)
    {
        socket = new WebSocket(connectionId, websocketheaders);

        socket.OnMessage += (sender, e) =>
        {
            if (OnMessage != null)
            {
                OnMessage.Invoke(e.Data);
            }
        };

        socket.OnOpen += (sender, e) =>
        {
            if (OnOpen != null)
            {
                OnOpen.Invoke();
            }
        };

        socket.OnError += (sender, e) =>
        {
            Debug.LogError(e.Exception);
        };

        socket.Connect();
    }
Beispiel #2
0
        internal void Update()
        {
            while (eventArgsQueue.Count > 0)
            {
                EventArgs e;
                lock (eventArgsQueue)
                {
                    e = eventArgsQueue.Dequeue();
                }

                if (e is CloseEventArgs && OnClose != null)
                {
                    OnClose.Invoke(this, e as CloseEventArgs);
                }
                else if (e is OpenEventArgs && OnOpen != null)
                {
                    OnOpen.Invoke(this, e as OpenEventArgs);
                }
                else if (e is MessageEventArgs && OnMessage != null)
                {
                    OnMessage.Invoke(this, e as MessageEventArgs);
                }
                else if (e is ErrorEventArgs && OnError != null)
                {
                    OnError.Invoke(this, e as ErrorEventArgs);
                }
            }
        }
 private void HandleOnOpen(object sender, EventArgs e)
 {
     if (OnOpen != null)
     {
         OnOpen.Invoke(sender, e);
     }
 }
Beispiel #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;
         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());
     }
 }
Beispiel #5
0
        private void OnConnected(IAsyncResult ar)
        {
            if (m_socket == null)
            {
                return;
            }

            Socket client = (Socket)ar.AsyncState;

            ar.AsyncWaitHandle.Close();
            try
            {
                lock (m_sync_lock)
                {
                    client.EndConnect(ar);
                    this.BeginReceive();
                    if (OnOpen != null)
                    {
                        OnOpen.Invoke(0);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("连接失败:" + e.Message);
                this.Close();
            }
        }
Beispiel #6
0
 internal void HandleOnOpen()
 {
     if (OnOpen != null)
     {
         OnOpen.Invoke(this, new OpenEventArgs());
     }
 }
Beispiel #7
0
    public async void OpenWebsocket(string url, List <KeyValuePair <string, string> > websocketheaders)
    {
        socket = new MessageWebSocket();

        socket.Closed += (sender, args) =>
        {
            Debug.Log("Stopped reason: " + args.Reason);
        };

        socket.MessageReceived += OnWebSocketMessage;

        socket.Control.MessageType              = SocketMessageType.Utf8;
        socket.ServerCustomValidationRequested += OnServerCustomValidationRequested;
        socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
        socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

        foreach (var header in websocketheaders)
        {
            socket.SetRequestHeader(header.Key, header.Value);
        }

        await socket.ConnectAsync(new Uri(url));

        messageWriter = new DataWriter(socket.OutputStream);

        if (OnOpen != null)
        {
            OnOpen.Invoke();
        }
    }
Beispiel #8
0
 private void RaiseOpen()
 {
     if (OnOpen != null)
     {
         OnOpen.Invoke(this, new EventArgs());
     }
 }
        private async Task StartHandshakeWithServer()
        {
            var httpEOF   = Encoding.UTF8.GetBytes("\r\n\r\n");
            var received  = new List <byte>();
            var buffer    = new byte[2048];
            var host      = uri.Host;
            var path      = uri.PathAndQuery;
            var eol       = "\r\n";
            var handshake = "GET " + path + " HTTP/1.1" + eol;

            handshake += "Host: " + host + eol;
            handshake += "Upgrade: websocket" + eol;
            handshake += "Connection: Upgrade" + eol;
            handshake += "Sec-WebSocket-Key: V2ViU29ja2V0Q2xpZW50" + eol;
            handshake += "Sec-WebSocket-Version: 13" + eol;
            handshake += eol;
            var handshakeBytes = Encoding.UTF8.GetBytes(handshake);
            await stream.WriteAsync(handshakeBytes, 0, handshakeBytes.Length);

            while (received.IndexOf(httpEOF) == -1)
            {
                var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);

                received.AddRange(buffer.Take(bytesRead));
            }
            OnOpen.Invoke(this, null);
            var doNotWait = StartReceivingFromServer();
        }
Beispiel #10
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) => {
            if (OnOpen != null)
            {
                OnOpen.Invoke(sender, e);
            }
            m_IsConnected = true;
        };

        m_Socket.OnClose += (sender, e) => {
            if (OnClose != null)
            {
                OnClose.Invoke(sender, e);
            }
        };

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

        m_Socket.ConnectAsync();

        while (!m_IsConnected && m_Error == null)
        {
            yield return(0);
        }
    }
Beispiel #11
0
 private void DoorOpen()
 {
     opened = true;
     if (OnOpen != null)
     {
         OnOpen.Invoke();
     }
 }
Beispiel #12
0
        /// <summary>
        /// open a drawer
        /// </summary>
        /// <returns></returns>
        public async Task OpenAsync()
        {
            await _service.OpenAsync(this);

            if (OnOpen != null)
            {
                await OnOpen.Invoke();
            }
        }
        /// <summary>
        /// open the notification box
        /// </summary>
        /// <returns></returns>
        public override async Task OpenAsync()
        {
            await _service.InternalOpen(Config);

            if (OnOpen != null)
            {
                await OnOpen.Invoke();
            }
        }
Beispiel #14
0
 /// <summary>
 /// Open UI.
 /// </summary>
 /// <param name="data">Data for UI.</param>
 public virtual void Open(object data = null)
 {
     if (data != null)
     {
         Refresh(data);
     }
     gameObject.SetActive(true);
     OnOpen.Invoke();
 }
Beispiel #15
0
        // Update is called once per frame
        void Update()
        {
            if (_threadOnOpen)
            {
                OnOpen.Invoke();
                _threadOnOpen = false;
            }
            if (_threadOnOpenFailed)
            {
                ErrorClose();
                OnOpenFailed.Invoke();
                _threadOnOpenFailed = false;
            }
            if (_threadOnErrorClosed)
            {
                ErrorClose();
                OnErrorClosed.Invoke();
                _threadOnErrorClosed = false;
            }
            if (_threadOnStartSearch)
            {
                OnStartSearch.Invoke();
                _threadOnStartSearch = false;
            }
            if (_threadOnStopSearch)
            {
                OnStopSearch.Invoke();
                _threadOnStopSearch = false;
            }
            if (_threadOnFoundDevice)
            {
                OnFoundDevice.Invoke(new CommDevice(foundDevices[foundDevices.Count - 1]));
                _threadOnFoundDevice = false;
            }
            if (_threadOnChangedDevice)
            {
                OnChangedDevice.Invoke(new CommDevice(device));
                _threadOnChangedDevice = false;
            }
            if (_threadOnWriteCompleted)
            {
                OnWriteCompleted.Invoke();
                _threadOnWriteCompleted = false;
            }

            if (_searchTimeout > 0f)
            {
                _searchTimeout -= Time.deltaTime;
                if (_searchTimeout <= 0f)
                {
                    StopSearch();
                }
            }
        }
Beispiel #16
0
 private void OnTriggerStay2D(Collider2D other)
 {
     if (other.gameObject.CompareTag("playerShadow") && Input.GetKeyDown(KeyCode.Joystick1Button1) && !_open)
     {
         _audioSource.clip = AudioList.Instance.opendoor_chest;
         _audioSource.Play();
         OnOpen.Invoke();
         _animator.SetBool("Open", true);
         _open = true;
     }
 }
Beispiel #17
0
        private async Task AcceptNewClient()
        {
            Console.WriteLine("WebSocketServer: Waiting for a new client connection...");
            var clientSocket = await socket.AcceptAsync();

            var stream = GetNetworkStream(clientSocket);
            var client = new SocketStream(clientSocket, stream);

            OnOpen.Invoke(this, client);
            Console.WriteLine($"WebSocketServer: A new client has connected {client.IP}:{client.Port}...");
            StartHandshakeWithClient(client);
            var doNotWait = AcceptNewClient();
        }
    private void BuyEventHandler(Interactor interactor)
    {
        if (interactor.TryGetComponent(out PlayerInventory inventory) &&
            inventory.TrySubtract(_cost))
        {
            OnHoverEnd();

            this.gameObject.SetActive(false);
            OnOpen.Invoke();

            Destroy(this.gameObject);
        }
    }
Beispiel #19
0
        public override void Open()
        {
            if (client != null)
            {
                sendQueue.Enqueue(() => client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Normal", token));

                //Task task =  client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Normal", token);
                //Task.WaitAll(task);
                client.Dispose();
            }


            client = new ClientWebSocket();


            if (!string.IsNullOrEmpty(subProtocol))
            {
                client.Options.AddSubProtocol(subProtocol);
            }

            if (!string.IsNullOrEmpty(securityToken) && this.subProtocol != "mqtt")
            {
                client.Options.SetRequestHeader("Authorization", String.Format("Bearer {0}", securityToken));
            }

            if (certificate != null)
            {
                client.Options.ClientCertificates.Add(certificate);
            }

            State = ChannelState.Connecting;

            try
            {
                sendQueue.Enqueue(() => client.ConnectAsync(endpoint, token));
                State           = ChannelState.Open;
                IsAuthenticated = true;

                OnOpen?.Invoke(this, new ChannelOpenEventArgs(Id, null));
            }
            catch (AggregateException ae)
            {
                State = ChannelState.Aborted;
                throw ae.Flatten();
            }
            catch (Exception ex)
            {
                State = ChannelState.Aborted;
                throw ex;
            }
        }
Beispiel #20
0
        public async Task Connect()
        {
            try
            {
                Log.Debug("Connecting to " + url);
                //if (ws != null && (ws.State == System.Net.WebSockets.WebSocketState.Aborted || ws.State == System.Net.WebSockets.WebSocketState.Closed))
                if (ws != null && (ws.State != WebSocketState.Connecting))
                {
                    ws.Dispose();
                    ws = null;
                }
                if (ws == null)
                {
                    // ws = new ClientWebSocket();
                    // ws = (ClientWebSocket)SystemClientWebSocket.CreateClientWebSocket();
                    if (VersionHelper.IsWindows8OrGreater())
                    {
                        // ws = new ClientWebSocket();
                        ws = new System.Net.WebSockets.Managed.ClientWebSocket();
                    }
                    else
                    {
                        ws = new System.Net.WebSockets.Managed.ClientWebSocket();
                    }
                    src = new CancellationTokenSource();
                }
                if (ws.State == System.Net.WebSockets.WebSocketState.Connecting || ws.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    return;
                }
                if (ws.State == System.Net.WebSockets.WebSocketState.CloseReceived)
                {
                    OnClose?.Invoke("Socket closing");
                    ws.Dispose();
                    ws = null;
                    return;
                }
                Log.Information("Connecting to " + url);
                await ws.ConnectAsync(new Uri(url), src.Token);

                Log.Information("Connected to " + url);
                Task receiveTask = Task.Run(async() => await receiveLoop(), src.Token);
                Task pingTask    = Task.Run(async() => await PingLoop(), src.Token);
                OnOpen?.Invoke();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "");
                OnClose?.Invoke(ex.Message);
            }
        }
Beispiel #21
0
 private void OpenDialog <T>(string title, Dictionary <string, object> parameters, DialogOptions options)
 {
     dialogs.Add(new object());
     OnOpen?.Invoke(title, typeof(T), parameters, new DialogOptions()
     {
         Width        = options != null && !string.IsNullOrEmpty(options.Width) ? options.Width : "600px",
         Left         = options != null && !string.IsNullOrEmpty(options.Left) ? options.Left : "",
         Top          = options != null && !string.IsNullOrEmpty(options.Top) ? options.Top : "",
         Height       = options != null && !string.IsNullOrEmpty(options.Height) ? options.Height : "",
         ShowTitle    = options != null ? options.ShowTitle : true,
         ShowClose    = options != null ? options.ShowClose : true,
         ChildContent = options?.ChildContent
     });
 }
Beispiel #22
0
        void Update()
        {
            if (_threadOnOpen)
            {
                OnOpen.Invoke();
                _threadOnOpen = false;
            }

            if (_threadOnOpenFailed)
            {
                OnOpenFailed.Invoke();
                _threadOnOpenFailed = false;
            }
        }
Beispiel #23
0
        private async Task AcceptNewClient()
        {
            Console.WriteLine("TCPServer: Waiting for a new client connection...");
            var socket = await this.socket.AcceptAsync();

            var remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
            var ip             = remoteEndPoint.Address;
            var port           = remoteEndPoint.Port;

            Console.WriteLine($"TCPServer: A new client has connected {ip}:{port}...");
            OnOpen.Invoke(this, socket);
            StartReceivingFromGameClient(socket);
            var doNotWait = AcceptNewClient();
        }
        public Task <bool> Connect()
        {
            if (!HasConnection)
            {
                OnError?.Invoke(new Exception("No connection"));
                return(Task.FromResult(false));
            }

            IsClosed = false;
            IsOpen   = true;
            OnOpen?.Invoke();

            return(Task.FromResult(true));
        }
Beispiel #25
0
    public IEnumerator Connect()
    {
        m_NativeRef = SocketCreate(mUrl.ToString());

        while (SocketState(m_NativeRef) == 0)
        {
            yield return(0);
        }

        if (OnOpen != null)
        {
            OnOpen.Invoke(this, new EventArgs());
        }
    }
Beispiel #26
0
        public override void Open()
        {
            server = toggle.isOn;
            if (server)
            {
                if (_server != null)
                {
                    return;
                }

                try
                {
                    _server = new TcpListener(IPAddress.Any, port);
                    _server.Start();
                    _server.BeginAcceptTcpClient(new AsyncCallback(AcceptTcpClientCallback), _server);
                    //       Debug.LogError("Server Open");
                    OnOpen.Invoke();
                }
                catch (Exception e)
                {
                    //       Debug.LogError("Server Open Failed");
                    //       Debug.LogError(e);
                    _server.Stop();
                    _server = null;
                    OnOpenFailed.Invoke();
                }
            }
            else
            {
                if (_client != null)
                {
                    return;
                }

                try
                {
                    _client = new TcpClient();
                    //      Debug.LogError("Client Begin Connect");
                    _client.BeginConnect(IPAddress.Parse(ipAddress), port, new AsyncCallback(ConnectCallback), _client);
                }
                catch (Exception e)
                {
                    //       Debug.LogError("Client Begin Connect Failed");
                    //       Debug.LogError(e);
                    _client.Close();
                    _client = null;
                    OnOpenFailed.Invoke();
                }
            }
        }
Beispiel #27
0
        internal void FireOpen()
        {
#if DEBUG_TCPIO
            Console.WriteLine("FireOpen: fire open (is server: {0})", isServer);
#endif
            if (Owner == null)
            {
                OnOpen?.Invoke();
            }
            else
            {
                Owner.FireConnection(this);
            }
        }
Beispiel #28
0
        public void Start()
        {
            if (IsConnected())
            {
                return;
            }

            _wsServer.Start(socket =>
            {
                WebSock          = socket;
                socket.OnOpen    = () => OnOpen?.Invoke();
                socket.OnClose   = () => OnClose?.Invoke();
                socket.OnMessage = (message) => OnMessage?.Invoke(message);
            });
        }
Beispiel #29
0
 public bool Initiate(byte[] trail)
 {
     lock (Sync)
     {
         if (Mode.FireOpen)
         {
             OnOpen?.Invoke();
         }
         if (!Parser.Write(trail))
         {
             return(false);
         }
         return(Base.Pipe(Parser));
     }
 }
Beispiel #30
0
    async Task StartAsync()
    {
        /*
         * // If we are connecting to wss:// endpoint, by default, the OS performs validation of
         * // the server certificate based on well-known trusted CAs. We can perform additional custom
         * // validation if needed.
         * if (SecureWebSocketCheckBox.IsChecked == true)
         * {
         *  // WARNING: Only test applications should ignore SSL errors.
         *  // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
         *  // attacks. (Although the connection is secure, the server is not authenticated.)
         *  // Note that not all certificate validation errors can be ignored.
         *  // In this case, we are ignoring these errors since the certificate assigned to the localhost
         *  // URI is self-signed and has subject name = fabrikam.com
         *  streamWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
         *  streamWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
         *
         *  // Add event handler to listen to the ServerCustomValidationRequested event. This enables performing
         *  // custom validation of the server certificate. The event handler must implement the desired
         *  // custom certificate validation logic.
         *  streamWebSocket.ServerCustomValidationRequested += OnServerCustomValidationRequested;
         *
         *  // Certificate validation is meaningful only for secure connections.
         *  if (server.Scheme != "wss")
         *  {
         *      AppendOutputLine("Note: Certificate validation is performed only for the wss: scheme.");
         *  }
         * }
         */

        try {
            Debug.Log("start of StartAsync");
            await socket.ConnectAsync(url);

            Debug.Log("middle of StartAsync");
        }
        catch (Exception ex) // For debugging
        {
            socket.Dispose();
            socket = null;

            //	gr: do error!
            OnError.Invoke(this, new ErrorEventArgs(ex.Message));
            return;
        }
        OnOpen.Invoke(this, null);
        Debug.Log("end of StartAsync");
    }