Implements the WebSocket interface.
The WebSocket class provides a set of methods and properties for two-way communication using the WebSocket protocol (RFC 6455).
Inheritance: IDisposable
Esempio n. 1
1
        public int ConnectToWebSocket()
        {
            ws = new WebSocket(_Address);

            timer = new System.Windows.Forms.Timer();
            timer.Interval = 1500;
            timer.Tick += (sender, e) =>
            {
                if (ws != null)
                    ws.Send(JsonConvert.SerializeObject(new { type = "getframe" }));
            };

            ws.OnMessage += Ws_OnMessage;
            ws.OnOpen += (sender, e) =>
            {
                //ws.Send(JsonConvert.SerializeObject(new { type = "getinfo" }));
                string msg = "{\"type\":\"getinfo\"}";
                ws.Send(msg);
            };
            ws.OnError += (sender, e) =>
                {
                    MessageBox.Show("Error during Websocket Connection: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ws.Close();
                    ws = null;
                    this.Dispose();
                };

            ws.Connect();
            if (Connected != null)
                Connected();
            timer.Start();

            return 0;
        }
        public HearbeatTransmitter(WebSocket socket, TimeSpan heartBeatInterval, Func<Dictionary<string, object>> onSendingHearbeat)
        {
            _socket = socket;
            _heartBeatInterval = heartBeatInterval;
            _onSendingHearbeat = onSendingHearbeat;

            Receive<string>(message =>
            {
                if (socket.ReadyState == WebSocketState.Open)
                {
                    var heartbeat = onSendingHearbeat();
                    heartbeat["$$Timestamp"] = DateTime.UtcNow;

                    var jsonPayload = JsonConvert.SerializeObject(new
                    {
                        Type = "Heartbeat",
                        Payload = heartbeat
                    });

                    socket.Send(jsonPayload);

                    Context.System.Scheduler.ScheduleTellOnce(heartBeatInterval, Self, "SendHeartbeat", Self);
                }
            }, msg => msg == "SendHeartbeat");
        }
 public MessageReceiver(WebSocket client, IMessageDecoder decoder, IMessageDecompressor decompressor)
 {
     mDecoder = decoder;
     mDecompressor = decompressor;
     mClient = client;
     mClient.OnMessage += OnMessage;
 }
Esempio n. 4
0
 void disConetc(System.Object _ws)
 {
     Debug.LogError("cccccccccccccc");
     WebSocketSharp.WebSocket _socket = (WebSocketSharp.WebSocket)_ws;
     Debug.Log("断开");
     _socket.Close();
 }
Esempio n. 5
0
    public void createLobby(int maxPlayers, string name, int id, string socketID, WebSocketSharp.WebSocket socketContext, string token = "-1")
    {
        int playerID = 1;

        if (token == "-1")
        {
            token = getToken();
        }
        // initialize a new lobby, player, and list of players
        Lobby  newLobby  = new Lobby(token, 4); // hard coded max players
        Player newPlayer = new Player(1, name, socketID, socketContext);

        newLobby.players = new List <Player>();

        newLobby.players.Add(newPlayer);
        lobbies[newLobby.id] = newLobby;

        // Create a packet to confirm creation of new lobby
        ConfirmationPacket confirmationPacket = new ConfirmationPacket();

        confirmationPacket.lobbyID  = newLobby.id;
        confirmationPacket.playerID = playerID;
        Send(JsonConvert.SerializeObject(confirmationPacket));

        Console.WriteLine(maxPlayers + name + id);
        Console.WriteLine("sending new lobby");
    }
Esempio n. 6
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());
     }
 }
Esempio n. 7
0
        /// <summary>
        /// Close socket
        /// </summary>
        public void Clear()
        {
            logger.Trace("");

            if (socket == null)
            {
                return;
            }

            try
            {
                if (socket.ReadyState == WebSocketState.Open)
                {
                    socket.Close();
                }

                socket.OnOpen    -= Socket_OnOpen;
                socket.OnClose   -= Socket_OnClose;
                socket.OnError   -= Socket_OnError;
                socket.OnMessage -= Socket_OnMessage;

                socket = null;
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "WebSocket Clear Exception");
            }
        }
Esempio n. 8
0
        private void Connect(IPAddress address, int port)
        {
            if (this.ws != null 
                && (this.ws.ReadyState == WebSocketState.Connecting || this.ws.ReadyState == WebSocketState.Open))
                return;

            if (this.ws != null)
            {
                this.ws.Close();
                this.ws = null;
            }

            this.ws = new WebSocket("ws://" + address + ":" + port + "/remote");
            this.ws.OnMessage += (sender, args) => { this.OnReceive(args.Data); };
            this.ws.OnError += (sender, args) =>
            {
                if (!this.ws.IsAlive)
                {
                    this.ws.Close();
                    this.ws.Connect();
                }
            };

            this.ws.Connect();

            if (this.ws.ReadyState == WebSocketState.Open)
            {
                this.Authenticate();

                this.refetchTimer = new Timer(this.Refetch, null, 0, 500);
            }
        }
Esempio n. 9
0
        private void _webSocket_OnClose(object sender, CloseEventArgs e)
        {
            switch (e.Code)
            {
            case StatusCloseNormal:
                _logger.Info("Socket closed");
                break;

            case StatusCloseUnexpected:
                _logger.Error("WebSocket closed unexpectedly.");
                break;

            default:        // Abnormal closure
                _logger.Error($"WebSocket closed abnormally with code ${e.Code}.");
                break;
            }

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

            _webSocket   = null;
            _isConnected = false;

            OnClose(e.Code);
        }
        public void Start()
        {
            var model = _modelService.getPendingModel();

            var thisChan = model.findByPath(_context.getPath());

            // 1 - récupérer l'ensemble des ports input (provided) qui ne sont pas à l'intérieur du noeud courrant
            // 2 - lancer un consumer dessus avec en suffixe d'url le path vers le port en question

            foreach (var remoteInputPort in _remoteInputPorts)
            {
                var websocket = new WebSocket(GetChanURI(remoteInputPort.getPath()));
                websocket.Connect();
                _remoteInputPortWebsockets.Add(remoteInputPort.getPath(), websocket);
            }

            foreach (var inputPort in _inputPorts)
            {
                var websocket = new WebSocket(GetChanURI(inputPort.getPath()));
                websocket.OnMessage += (sender, data) =>
                {
                    inputPort.send(data.Data, null);
                };

                websocket.Connect();
                _inputPortWebsockets.Add(inputPort.getPath(), websocket);
            }
        }
Esempio n. 11
0
        public void connect(string url, string[] protocols, JObject options, int id)
        {
            if (options != null && options.ContainsKey("origin"))
            {
                throw new NotImplementedException(/* TODO: (#253) */);
            }

            var webSocket = new WebSocketSharp.WebSocket(url);

            webSocket.OnMessage += (sender, args) =>
            {
                OnMessageReceived(id, sender, args);
            };

            webSocket.OnOpen += (sender, args) =>
            {
                OnOpen(id, webSocket, args);
            };

            webSocket.OnError += (sender, args) =>
            {
                OnError(id, args);
            };

            webSocket.OnClose += (sender, args) =>
            {
                OnClosed(id, sender, args);
            };

            InitializeInBackground(id, url, webSocket);
        }
Esempio n. 12
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);
        }
    }
Esempio n. 13
0
		public void Awake()
		{
			encoder = new Encoder();
			decoder = new Decoder();
			parser = new Parser();
			handlers = new Dictionary<string, List<Action<SocketIOEvent>>>();
			ackList = new List<Ack>();
			sid = null;
			packetId = 0;

			ws = new WebSocket(url);
			ws.OnOpen += OnOpen;
			ws.OnMessage += OnMessage;
			ws.OnError += OnError;
			ws.OnClose += OnClose;
			wsConnected = false;

			eventQueueLock = new object();
			eventQueue = new Queue<SocketIOEvent>();

			ackQueueLock = new object();
			ackQueue = new Queue<Packet>();

			connected = false;

			#if SOCKET_IO_DEBUG
			if(debugMethod == null) { debugMethod = Debug.Log; };
			#endif
		}
Esempio n. 14
0
        public void InitServerInfo(string serverIp, string serverPort)
        {
            IsOpenned = false;
            L4Logger.Info("BCR InitServerInfo");
            if (_WebSocket != null)
            {
                _WebSocket.Close();
                _WebSocket.OnMessage -= _WebSocket_OnMessage;
            }
            this.ServerIP   = serverIp;
            this.ServerPort = serverPort;

            _WebSocket            = new WebSocketSharp.WebSocket(string.Format("ws://{0}:{1}/XfsCommandBehavior", ServerIP, ServerPort));
            _WebSocket.OnMessage += _WebSocket_OnMessage;
            _WebSocket.OnClose   += _WebSocket_OnClose;
            _WebSocket.OnError   += _WebSocket_OnError;
            _WebSocket.Connect();

            ReadDataCompleted = null;
            ReadDataError     = null;
            OpenCompleted     = null;
            RegisterCompleted = null;
            OpenError         = null;
            RegisterError     = 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();
        }
Esempio n. 16
0
 public Player(int id, string name, string socketID, WebSocketSharp.WebSocket webSocket)
 {
     this.id        = id;
     this.name      = name;
     this.socketID  = socketID;
     this.webSocket = webSocket;
 }
        public int Connect(string node_url = "")
        {
            var connectionString = node_url.Equals(string.Empty) ? Consts.WssConnectionString : node_url;
            var certList         = GetCertificatesFromPem(Consts.CertFileName);

            _wss = new WebSocketSharp.WebSocket(connectionString);

            _wss.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
            _wss.SslConfiguration.ClientCertificates  = new X509CertificateCollection(certList);
            _wss.SslConfiguration.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) => {
                // If the server certificate is valid.
                return(sslPolicyErrors == SslPolicyErrors.None);
            };

            _wss.OnMessage += (sender, e) => {
                var payload = e.Data;
                _logger.Info($"WS Received Message: {payload}");
                foreach (var item in _observers)
                {
                    item.HandleMessage(payload);
                }
            };

            _wss.Connect();
            _logger.Info($"Connected to {connectionString}");

            return(0);
        }
Esempio n. 18
0
        private async Task ConnectInternalAsync([NotNull] string host)
        {
            await DisconnectInternalAsync().ConfigureAwait(false);

            this.CancelTokenSource = new CancellationTokenSource();
            this.CancelToken       = CancellationTokenSource.CreateLinkedTokenSource
                                     (
                this.ParentToken,
                this.CancelTokenSource.Token
                                     )
                                     .Token;

            this.Client = new SharpSocket(host)
            {
                CustomHeaders = this.Headers.ToList()
            };
            this.Client.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls12;

            this.Client.OnMessage += OnMessage;
            this.Client.OnOpen    += OnConnected;
            this.Client.OnClose   += OnClosed;

            this.Client.Connect();
            this.WaitUntilConnect.Wait(this.CancelToken);
        }
Esempio n. 19
0
 public void Close() {
   _st = State.Dispose;
   _reconn.Change(-1, -1);
   Send("41");
   _ws.Close(CloseStatusCode.Normal);
   _ws = null;
 }
Esempio n. 20
0
 //needs to implemented from API
 /// <summary>
 /// 
 /// </summary>
 /// <param name="MessageReceived"></param>
 public ChatController(Model m)
 {
     ws = new WebSocket("ws://127.0.0.1:8005/chat");
     ws.OnMessage += (s, e) => GotPacket(e.Data);
     ws.Connect();
     this.m = m;
 }
Esempio n. 21
0
        private void BeginWebSocketClient(string stream, ICollection <ISymbol> symbols)
        {
            var newStreams = symbols.Select(s => $"{(Exchange.GetCurrencyCode(s.BaseCurrencyCode) + Exchange.GetCurrencyCode(s.QuoteCurrencyCode)).ToLower()}@{stream}");

            Streams.UnionWith(newStreams);

            if (WebSocketClient != null)
            {
                WebSocketClient = null;
            }

            WebSocketClient = new WebSocketSharp.WebSocket($"{Url}/stream?streams={string.Join('/', Streams)}");

            WebSocketClient.OnOpen += OnOpen;

            WebSocketClient.OnMessage += OnMessage;

            WebSocketClient.OnClose += delegate(object sender, WebSocketSharp.CloseEventArgs e)
            {
                OnClose?.Invoke(sender, new CloseEventArgs
                {
                    Code   = e.Code,
                    Reason = e.Reason
                });
            };

            WebSocketClient.Connect();
        }
Esempio n. 22
0
        public void ConnectToServer(string url, string key)
        {
            _ws = new WebSocket("ws://"+url);
            _ws.Origin = "http://agar.io";
            _ws.Log.Level = LogLevel.None;

            _ws.OnMessage += (sender, e) => {
                _dataMutex.WaitOne();
                _dataQueue.Enqueue(e.RawData);
                _dataMutex.ReleaseMutex();
            };

            _ws.OnError += (sender, e) => {
                Console.WriteLine(e.Message);
            };

            _ws.OnOpen += (sender, e) =>
            {
                _open = true;

                this.SendHandShake(key);

                Console.WriteLine("Connection opened to " + url + " - " + key);

            };

            _ws.Connect();
        }
Esempio n. 23
0
        /* WS */
        public ScarletMetrics()
        {
            metricsws = new WebSocket("ws://" + MetricsWSURL + ":" + MetricsWSPort);

            metricsws.Connect();

            metricsws.OnOpen += (sender, e) =>
            {
                // Metrics - On Connection to the Metrics WS Reporting Server
                // Need to include username / IP in here as well.
                JsonObject jsonMessage = new JsonObject()
                    .add("type", "metrics")
                    .add("message", "connected");
                metricsws.Send(jsonMessage.ToString());
            };

            metricsws.OnMessage += (sender, e) =>
            {
            };

            metricsws.OnClose += (sender, e ) =>
                metricsws.Connect();

            metricsws.OnError += (sender, e) =>
                metricsws.Connect();
        }
Esempio n. 24
0
    public static void Connect(string url)
    {
        if (_webSocket == null)
        {
            _webSocket = new WebSocketSharp.WebSocket("ws://" + url + "/Echo");

            // Set the WebSocket events.
            _webSocket.OnMessage += (sender, e) =>
            {
                _instance.OnMessageReceived(e.Data);
            };

            _webSocket.OnError += (sender, e) =>
            {
                _instance.OnError(e.Message);
            };

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

            _webSocket.Connect();
        }
    }
        public static void pushSocket(string socketUrl, JObject socketObj)
        {
            if (ws == null)
            {
                ws = new WebSocketSharp.WebSocket(socketUrl);
            }
            if (ws.IsAlive == false)
            {
                LogClasses.LogProperties.info("WebSocket Is Alive : " + ws.IsAlive.ToString());
                ws.Connect();
            }

            if (ws.IsAlive == true)
            {
                LogClasses.LogProperties.info("socket data send: " + socketObj.ToString());
                ws.Send(socketObj.ToString());
            }
            ws.OnMessage += (sender, e) =>
            {
                LogClasses.LogProperties.info("WebSocket OnMessage : " + e.Data.ToString());
            };
            ws.OnClose += (sender, e) =>
            {
                LogClasses.LogProperties.error("WebSocket OnClose : CODE IS " + e.Code.ToString() + " reason is " + e.Reason.ToString());
                ws.Connect();
            };
            ws.OnError += (sender, e) =>
            {
                LogClasses.LogProperties.error("WebSocket OnError exception : " + e.Exception.ToString() + " message is : " + e.Message.ToString());
            };
        }
Esempio n. 26
0
        public void connect(string url, string[] protocols, JObject options, int id)
        {
            var webSocket = new WebSocketSharp.WebSocket(url);

            webSocket.OnMessage += (sender, args) =>
            {
                OnMessageReceived(id, sender, args);
            };

            webSocket.OnOpen += (sender, args) =>
            {
                OnOpen(id, webSocket, args);
            };

            webSocket.OnError += (sender, args) =>
            {
                OnError(id, args);
            };

            webSocket.OnClose += (sender, args) =>
            {
                OnClosed(id, sender, args);
            };

            InitializeInBackground(url, webSocket, options);
        }
Esempio n. 27
0
        /// <summary>
        /// Connect in background
        /// </summary>
        private static void ConnectBackground()
        {
            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                while (Program.client == null)
                {
                    try
                    {
                        WS.WebSocket client = new WS.WebSocket(Program.appSettings.WebsocketServerAddress);
                        client.WaitTime     = new TimeSpan(0, 0, 30);
                        client.Connect();

                        if (client.ReadyState != WS.WebSocketState.Open)
                        {
                            Program.client = null;
                        }
                        else
                        {
                            client.OnClose += (sender, e) => Program.ConnectBackground();
                            Program.client  = client;
                        }
                    }
                    catch (Exception ex)
                    {
                        Program.client = null;
                        ex.ToString();
                    }
                }
            }).Start();
        }
Esempio n. 28
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Application.ActiveSheet);
            Excel.Range firstRow = activeWorksheet.get_Range("A1");
            firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
            Excel.Range newFirstRow = activeWorksheet.get_Range("A1");
            newFirstRow.Value2 = "lETS START THIS THING";

            //lets start this thing
            using (var ws = new WebSocket("ws://dumbsocket.herokuapp.com"))
            {
                ws.OnError += (error_sender, error_e) => {
                    Console.Write("socket error");
                    //SOME BROKE SHIT
                };

                ws.OnOpen += (open_sender, open_e) => {
                    Console.Write("sockets open");
                   //windows open
                };

                ws.OnClose += (close_sender, close_e) => {
                    Console.Write("socket closed");
                };

                ws.OnMessage += (socket_sender, socket_e) =>
                {
                    newFirstRow.Value2 = "This is coming from the websocket" + socket_e.Data;
                };

                ws.Connect();
            }
        }
Esempio n. 29
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());
        }
    }
Esempio n. 30
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();
        }
Esempio n. 31
0
        public Task Begin() => Task.Run(() =>
        {
            if (WebSocketClient != null)
            {
                throw new Exception("WebSocket already in use");
            }

            Channels = new Dictionary <long, SubscriptionEventResponse>();

            WebSocketClient = new WebSocketSharp.WebSocket(Url);

            WebSocketClient.OnOpen += OnOpen;

            WebSocketClient.OnMessage += OnMessage;

            WebSocketClient.OnClose += delegate(object sender, WebSocketSharp.CloseEventArgs e)
            {
                Channels = new Dictionary <long, SubscriptionEventResponse>();

                OnClose?.Invoke(sender, new CloseEventArgs {
                });
            };

            Connect();
        });
Esempio n. 32
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);
        }
    }
Esempio n. 33
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);
        }
 public void Websock_Client_Node()
 {
     if (Connect_Disconnect == false)
     {
         try
         {
             WebSocketClient            = new WebSocketSharp.WebSocket(serverUri.ToString());
             WebSocketClient.OnMessage += wsServer_NewDataReceived;
             WebSocketClient.OnOpen    += wsServer_NewSessionConnected;
             WebSocketClient.OnError   += wsServer_OnError;
             WebSocketClient.OnClose   += wsServer_Disconnect;
             WebSocketClient.Connect();
             Console.WriteLine("Connection Open");
             Connect_Disconnect = true;
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
             Connect_Disconnect = false;
         }
     }
     else
     {
         WebSocketClient.Send("User is already connected");
     }
 }
Esempio n. 35
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);
    }
Esempio n. 36
0
        public static void Main(string[] args)
        {
            if (args.Length != 1) {
                Console.Error.WriteLine ("ERROR: need a valid Websocket URL");
                Environment.Exit (-1);
            }

            using (var ws = new WebSocket (args[0])) {
                Int64 syncCtr = 0;
                ws.OnMessage += (sender, e) => {
                    Console.WriteLine (e.Data);
                    Interlocked.Decrement (ref syncCtr);
                };
                ws.Connect ();
                if (!ws.IsAlive) {
                    Console.Error.WriteLine ("ERROR: Could not connect to Websocket Server {0}", args[0]);
                    Environment.Exit(-2);
                }

                var input = "";
                while (string.Compare (input.Trim (), "shutdown", true) != 0) {
                    if (!string.IsNullOrWhiteSpace (input)) {
                        ws.Send (input.Trim());
                        Interlocked.Increment (ref syncCtr);

                        while (Interlocked.Read (ref syncCtr) > 0) {
                            Thread.Sleep (1);
                        }
                    }
                    Console.Write ("Type in a message or 'shutdown' to quit: ");
                    input = Console.ReadLine ();
                } // Longevity loop
            } // using
        }
Esempio n. 37
0
        public void Connect(string url)
        {
            DisposeCurrentConnection();

            if (IsConnected)
            {
                Close();
            }

            var ws = new WebSocket(url);
            ws = new WebSocket(url);
            ws.OnOpen += OnOpen;
            ws.OnMessage += OnMessage;
            ws.OnError += OnError;
            ws.OnClose += OnClose;
            _isWsConnected = false;

            _socketWorker = new WebSocketWorker(ws, RunSocketThread);
            _socketWorker.Start();

            _pingWorker = new WebSocketWorker(ws, RunPingThread);
            _pingWorker.Start();
        
            _ws = ws;
        }
Esempio n. 38
0
        public void ReConnectWebSocket(string Address)
        {
            if( Socket != null )
                Socket.Close();

            Socket = null;
            ConnectWebSocket(Address);
        }
Esempio n. 39
0
 public Session(World world)
 {
     _open = false;
     _ws = null;
     _world = world;
     _dataQueue = new Queue<byte[]>();
     _dataMutex = new Mutex();
 }
Esempio n. 40
0
 public void Start(string address, int port, string path)
 {
     // IPAddress ipaddr = new IPAddress(address.Split('.').Select(a => (byte)a.to_i()).ToArray());
     // WebSocketServer wss = new WebSocketServer(ipaddr, port, this);
     wsc = new WebSocket(address + ":"+port+path, this);
     wsc.OnMessage += OnMessage;
     wsc.Connect();
 }
 public WebSocketClientChannel(WebSocketSharp.WebSocket socket)
 {
     this._socket    = socket;
     this._onClosed += (o, e) =>
     {
         this.Close(e.Reason);
     };
 }
        public WebSocketSharpSocket(string url)
        {
            URL = url;

            Socket = new WebSocket(url);

            HookupEvents();
        }
Esempio n. 43
0
 public WsObject init(string address, string initMessage)
 {
     this.webSocket          = new WebSocketSharp.WebSocket(address);
     this.initMessage        = initMessage;
     this.webSocket.WaitTime = new TimeSpan(0, 0, 2);
     this.connect();
     return(this);
 }
Esempio n. 44
0
 void OnApplicationQuit()
 {
     if (wsClient != null)
     {
         wsClient.Close();
         wsClient = null;
     }
 }
Esempio n. 45
0
 public BitfinexWebsocketAPI(IObjectSpace space)
 {
     Count           = 0;
     Space           = space;
     CurrentExchange = Space.FindObject <Exchange>(new BinaryOperator("Name", "Bitfinex"));
     Socket          = new WebSocketSharp.WebSocket("wss://api.bitfinex.com/ws/2");
     // Authenticate();
 }
Esempio n. 46
0
 public WebSocketClientChannel(WebSocketSharp.WebSocket socket)
 {
     this._socket = socket;
     this._onClosed += (o, e) =>
     {
         this.Close(e.Reason);
     };
 }
Esempio n. 47
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();
 }
 private void OnApplicationExit(object sender, EventArgs e)
 {
     if (_client != null)
     {
         _client.Close();
         _client = null;
     }
 }
Esempio n. 49
0
        public WebSocketClient(IMessageInterpreter interpreter, string url)
        {
            _interpreter = interpreter;

            _webSocket = new WebSocket(url);
            _webSocket.Log.Level = SlackConnector.LoggingLevel == ConsoleLoggingLevel.FatalErrors ? LogLevel.Fatal : LogLevel.Trace;
            _webSocket.OnMessage += WebSocketOnMessage;
            _webSocket.OnClose += (sender, args) => OnClose?.Invoke(sender, args);
        }
Esempio n. 50
0
        public void ConnectWebSocket(string Address)
        {
            Socket = new WebSocket(Address, "connection");
            Socket.OnOpen += ServerToClientConnected;
            Socket.OnMessage += ServerToClientOnMessage;
            Socket.OnClose += ServerToClientDisconnected;

            Socket.Connect();
        }
Esempio n. 51
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();
 }
        public NativeWebSocketClient(string url)
        {
            Connection = new WebSocketSharp.WebSocket(url);

            Connection.OnOpen    += OnOpen;
            Connection.OnMessage += OnMessage;
            Connection.OnError   += OnError;
            Connection.OnClose   += OnClose;
        }
Esempio n. 53
0
        public AudioStreamer(string url)
        {
            _ws       = new WebSocket(url);
              _msgQ     = Queue.Synchronized(new Queue());
              _audioBox = new Dictionary<uint, Queue>();
              _user_id  = null;

              configure();
        }
Esempio n. 54
0
 private void button1_Click(object sender, EventArgs e)
 {
     ws = new WebSocket("ws://localhost:8080/?id=" + txtName.Text);
     ws.OnOpen += new EventHandler(ws_OnOpen);
     ws.OnMessage += new EventHandler<MessageEventArgs>(ws_OnMessage);
     ws.OnError += new EventHandler<ErrorEventArgs>(ws_OnError);
     ws.OnClose += new EventHandler<CloseEventArgs>(ws_OnClose);
     ws.Connect();
 }
Esempio n. 55
0
    private WebSocket(Uri url, WebSocketSharp.WebSocket socket)
    {
        _url    = url;
        _socket = socket;

        // Register the listeners for incoming messages/errors.
        _socket.OnMessage += OnMessage;
        _socket.OnError   += OnError;
    }
Esempio n. 56
0
		private void StartWebSocket ()
		{
			webSocket = new WebSocket (wsUri.AbsoluteUri);
			webSocket.Connect ();
			webSocket.OnOpen += WebSocket_OnOpen;
			webSocket.OnMessage += WebSocket_OnMessage;
			webSocket.OnClose += WebSocket_OnClose;
			webSocket.OnError += WebSocket_OnError;
		}
Esempio n. 57
0
        public Sockets(Form1 forma)
        {
            this.forma = forma;
            WS = new WebSocket("ws://localhost:4649/Actina");

            WS.OnOpen += conexionAbierta;
            WS.OnMessage += (sender, e) => forma.mensajeRecibido(e.Data);
            WS.OnClose += WS_OnClose;
            WS.OnError += WS_OnError;
        }
        public AudioStreamer(string url)
        {
            _websocket = new WebSocket (url);

              _audioBox = new Dictionary<uint, Queue> ();
              _id = null;
              _notifier = new Notifier ();
              _timer = new Timer (sendHeartbeat, null, -1, -1);

              configure ();
        }
Esempio n. 59
0
        public static void Main(string[] args)
        {
            //using (WebSocket ws = new WebSocket("ws://localhost:8000/"))
              using (WebSocket ws = new WebSocket("ws://localhost:8000/", "chat"))
              {
            /*ws.OnOpen += (o, e) =>
            {
              //Do something.
            };
             */
            ws.OnMessage += (o, s) =>
            {
            #if NOTIFY
              Notification nf = new Notification("[WebSocket] Message",
                                             s,
                                             "notification-message-im");
              nf.AddHint("append", "allowed");
              nf.Show();
            #else
              Console.WriteLine("[WebSocket] Message: {0}", s);
            #endif
            };

            ws.OnError += (o, s) =>
            {
              Console.WriteLine("[WebSocket] Error  : {0}", s);
            };

            /*ws.OnClose += (o, e) =>
            {
              //Do something.
            };
             */
            ws.Connect();

            Thread.Sleep(500);
            Console.WriteLine("\nType \"exit\" to exit.\n");

            string data;
            while (true)
            {
              Thread.Sleep(500);

              Console.Write("> ");
              data = Console.ReadLine();
              if (data == "exit")
              {
            break;
              }

              ws.Send(data);
            }
              }
        }
Esempio n. 60
0
 public void Init(string path,
                 string id)
 {
     if (ws != null && ws.IsAlive)
         ws.Close();
     ws = new WebSocket(path + id);//ws://localhost:8080/?name=
     ws.OnOpen += new EventHandler(ws_OnOpen);
     ws.OnMessage += new EventHandler<MessageEventArgs>(ws_OnMessage);
     ws.OnClose += new EventHandler<CloseEventArgs>(ws_OnClose);
     ws.OnError += new EventHandler<ErrorEventArgs>(ws_OnError);
 }