Пример #1
0
        private static void InitializeConnection()
        {
            var server = new WebSocketServer("ws://0.0.0.0:8181");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    _clients.Add(socket);
                };

                socket.OnClose = () =>
                {
                    _clients.Remove(socket);
                };

                socket.OnMessage = message =>
                {
                    switch (message)
                    {
                        case "Color":
                            _mode = Mode.Color;
                            break;
                        case "Depth":
                            _mode = Mode.Depth;
                            break;
                        default:
                            break;
                    }

                    Console.WriteLine("Switched to " + message);
                };
            });
        }
Пример #2
0
        public void Start()
        {
            List <IWebSocketConnection> sockets = new List <IWebSocketConnection>();

            Fleck.WebSocketServer server = new Fleck.WebSocketServer("ws://127.0.0.1:8181");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Connection open.");
                    sockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Connection closed.");
                    sockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine("Client says: " + message);
                    sockets.ToList().ForEach(s => s.Send(" client says:" + message));
                };
            });

            string input = Console.ReadLine();

            while (input != "exit")
            {
                sockets.ToList().ForEach(s => s.Send(input));
                input = Console.ReadLine();
            }
        }
Пример #3
0
    public bool StartWebSocketServer() {
      WSRConfig cfg = WSRConfig.GetInstance();

      int port = cfg.WebSocket;
      if (port < 0) { return false; }

      if (cfg.WSSmooth)  filter1 = new DepthFilteredSmoothing();
      if (cfg.WSAverage) filter2 = new DepthAveragedSmoothing();

      ImageFormat format = cfg.WSType == "png" ? ImageFormat.Png : ImageFormat.Jpeg;

      Sockets = new List<IWebSocketConnection>();
      Server = new WebSocketServer("ws://localhost:" + port);
      Server.Start(socket => {
        socket.OnOpen = () => {
          cfg.logInfo("WEBSCK", "Connected to: " + socket.ConnectionInfo.ClientIpAddress);
          lock (Sockets) { Sockets.Add(socket); }
        };
        socket.OnClose = () => {
          cfg.logInfo("WEBSCK", "Disconnected from: " + socket.ConnectionInfo.ClientIpAddress);
          lock (Sockets) { Sockets.Remove(socket); }
        };
        socket.OnMessage = message => {
          SendWebSocket(socket, GreenScreen(message), format);
        };
      });
      return true;
    }
Пример #4
0
        public ChatHandler()
        {
            chatSocketList = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://localhost:5002/chat");
            server.Start(socket =>
            {
                socket.OnOpen = () => {
                    Console.WriteLine("User connected to Chat");
                    chatSocketList.Add(socket);
                    //socket.Send(JsonConvert.SerializeObject(Main.ludo.Chat));
                };

                socket.OnClose = () => {
                    chatSocketList.Remove(socket);
                };

                socket.OnMessage = message =>
                {
                    Console.WriteLine("[ChatHandler] Incoming: " + message);
                    Message msg = JsonConvert.DeserializeObject<Message>(message);
                    msg.TimeStamp = DateTime.Now;
                    Main.ludo.Chat.Add(msg);
                    foreach (var s in chatSocketList.ToList())
                    {
                        s.Send(JsonConvert.SerializeObject(msg));
                    }
                };
            });
        }
Пример #5
0
        public void Start()
        {
            Fleck.WebSocketServer server = new Fleck.WebSocketServer("ws://localhost:8181");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Connection open.");
                    this._sockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Connection closed");
                    this._sockets.Remove(socket);
                };
            });

            this._stocks = Builder <Stock> .CreateListOfSize(1000).WhereAll().Build();

            if (this._timer == null)
            {
                this._timer = new Timer(SendStock, null, 0, 1500);

                Console.WriteLine("");
                Console.WriteLine("Sending stock info to all connected clients.");
            }

            Console.ReadLine();
        }
Пример #6
0
        public void Start()
        {
            Fleck.WebSocketServer server = new Fleck.WebSocketServer("ws://0.0.0.0:62127");

            server.Start(socket =>
            {
                Connection connection = new Connection(this, socket);

                lock (readLock)
                {
                    connections.Add(connection);
                }

                connection.Start();

                gameManager.OnJoin(connection);
            }
                         );

            // Sleep. Sleep the peace of the dead.
            System.Threading.Thread.Sleep(-1);

            //while (true) // We will never ever exit
            //    Console.ReadLine();
        }
Пример #7
0
        private void Initialize()
        {
            var server = new WebSocketServer("ws://0.0.0.0:8282");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    _clients.Add(socket);
                };

                socket.OnClose = () =>
                {
                    _clients.Remove(socket);
                };

                socket.OnMessage = message =>
                {
                    //var eventObject = Serialization.DeserializeEnvelope<ContractMarker>(message);
                    //_commandReceivedSubject.OnNext(eventObject);

                    Tracer.Trace(message);
                };

                socket.OnBinary = data =>
                {
                    Tracer.Trace("Binary data sent from client o_0");
                };
            });
        }
Пример #8
0
        public void StartServer()
        {
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://localhost:8181");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    //Console.WriteLine("Open!");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    //Console.WriteLine("Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    var date = DateTime.Now.ToShortTimeString();
                    //SaveMessage(socket.ConnectionInfo.Id, message);
                    //Console.WriteLine(message);
                    allSockets.ToList().ForEach(s => s.Send(date + ": " + message));
                };
            });

            //server.Close();

            //ServiceHost host = new ServiceHost(typeof(MyService));
        }
Пример #9
0
 public static void init()
 {
     FleckLog.Level = LogLevel.Debug;
     allSockets = new List<IWebSocketConnection>();
     server = new WebSocketServer("ws://localhost:1337");
     server.Start(socket =>
     {
         socket.OnOpen = () =>
         {
             Console.WriteLine("Open!");
             allSockets.Add(socket);
         };
         socket.OnClose = () =>
         {
             Console.WriteLine("Close!");
             allSockets.Remove(socket);
         };
         socket.OnMessage = message =>
         {
             Console.WriteLine(message);
             if (message == "SENDMEANIMAGE")
             {
                 Kinect.sendImage();
             }
         };
     });
 }
Пример #10
0
        private static void InitializeServer()
        {
            var server = new WebSocketServer("ws://localhost:8181");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Connected to " + socket.ConnectionInfo.ClientIpAddress);
                    _clients.Add(socket);
                };

                socket.OnClose = () =>
                {
                    Console.WriteLine("Disconnected from " + socket.ConnectionInfo.ClientIpAddress);
                    _clients.Remove(socket);
                };

                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                };
            });

            _serverInitialized = true;

            Console.ReadLine();
        }
Пример #11
0
        public void Run(string serverUrl)
        {
            var server = new WebSocketServer(serverUrl);
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    onClientConnected(socket);
                };

                socket.OnClose = () =>
                {
                    onClientDisconnected(socket, null);
                };

                socket.OnMessage = (message) =>
                {
                    onClientMessage(socket, message, null);
                };

                socket.OnBinary = (message) =>
                {
                    onClientMessage(socket, message, null);
                };
            });
        }
        public void InitializeSockets()
        {
            _sockets = new List<IWebSocketConnection>();

            var server = new WebSocketServer("ws://localhost:8181");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    _sockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    _sockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    JavaScriptSerializer js = new JavaScriptSerializer();

                    dynamic obj = js.Deserialize<object>(message);
                    dynamic listaComandos = obj["Palabras"];
                    Audio.añadirComandos(listaComandos);
                };
            });
        }
Пример #13
0
        public void InitializeListener()
        {
            var server = new WebSocketServer("ws://localhost:8989/FileTail");

            server.Start(socket =>
            {
                socket.OnOpen = () => Console.WriteLine("Open!");
                socket.OnClose = () => Console.WriteLine("Close!");
                socket.OnMessage = message => socket.Send(message);
            });

            //var listener = new TcpListener(IPAddress.Loopback, 8989);
            //try
            //{
            //    listener.Start();
            //    using (var client = listener.AcceptTcpClient())
            //    using (var stream = client.GetStream())
            //    using (var reader = new StreamReader(stream))
            //    using (var writer = new StreamWriter(stream))
            //    {
            //        writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
            //        writer.WriteLine("Upgrade: WebSocket");
            //        writer.WriteLine("Connection: Upgrade");
            //        writer.WriteLine("WebSocket-Origin: http://localhost:50695");
            //        writer.WriteLine("WebSocket-Location: ws://localhost:8989/websession");
            //        writer.WriteLine("");
            //    }
            //    listener.Stop();
            //}
            //catch
            //{ }
        }
        static void Main(string[] args)
        {
            var webSocketServer = new WebSocketServer("ws://127.0.0.1:8081");
            var sockets = new List<IWebSocketConnection>();

            webSocketServer.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    sockets.Add(socket);
                };

                socket.OnMessage = mensagem =>
                {
                    foreach (var s in sockets)
                    {
                        s.Send(mensagem);
                    }
                };

                socket.OnClose = () =>
                {
                    sockets.Remove(socket);
                };
            });

            Console.ReadKey();
        }
Пример #15
0
        static void Main(string[] args)
        {
            var server = new WebSocketServer("ws://localhost:8181");
            server.Start(socket =>
            {
                socket.OnOpen = () => 
                    {
                        Console.WriteLine("Open: " + socket.ConnectionInfo.Id);
                    };
                socket.OnClose = () => 
                    {
                        Console.WriteLine("Close: " + socket.ConnectionInfo.Id);

                        ChatServer.Instance.ClientLost(socket);
                    };
                socket.OnMessage = message =>
                {
                    Console.WriteLine("Message: " + socket.ConnectionInfo.Id);
                    Console.WriteLine("    " + message);

                    ChatServer.Instance.Accept(socket, message);
                };
            });

            Console.ReadLine();
        }
Пример #16
0
        static void Main()
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://0.0.0.0:8181");

            server.Start(socket =>
                {
                    socket.OnOpen = () =>
                        {
                            Console.WriteLine("Open!");
                            allSockets.Add(socket);
                        };
                    socket.OnClose = () =>
                        {
                            Console.WriteLine("Close!");
                            allSockets.Remove(socket);
                        };
                    socket.OnMessage = message =>
                        {
                            Console.WriteLine(message);

                            // process the message
                            dynamic gameState = gameServer.MessageBroker.ProcessMessage(message);
                            string serializedState = _serializer.Serialize(gameState);
                            //allSockets.ToList().ForEach(s => s.Send("Echo: "));
                        };
                });

            var input = Console.ReadLine();
            while (input != "exit")
            {
                input = Console.ReadLine();
            }
        }
Пример #17
0
        public static void Start()
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://0.0.0.0:8181");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Debug.WriteLine("Open!");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Debug.WriteLine("Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    var jsonObj = serializer.Deserialize<MessageFormat>(message);
                    Debug.WriteLine("[username]: " + jsonObj.username);
                    Debug.WriteLine("[nickname]: " + jsonObj.nickname);
                    Debug.WriteLine("[content]: " + jsonObj.content);
                    Debug.WriteLine("");
                    string msg = String.Format("{0}: {1}", jsonObj.nickname, jsonObj.content);
                    allSockets.ToList().ForEach(s => s.Send(msg));
                };
            });
        }
Пример #18
0
        static void Main()
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://localhost:8181");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("连接成功");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("连接已关闭");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine("客户端发来消息"+message);
                    //allSockets.ForEach(s => s.Send(message));
                };
            });

            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
Пример #19
0
        public void SendData()
        {
            var server = new Fleck.WebSocketServer("ws://127.0.0.1:8081/");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                };

                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    if (message.StartsWith("Venda"))
                    {
                        string[] dados = message.Split('|');

                        //abrir conexão com o banco de dados SQL.
                        //Verificar o pedido

                        //Resposta para o cliente
                        socket.Send("Confirmado");
                    }
                };

                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                };
            });

            Console.ReadKey();
        }
Пример #20
0
        public void Start()
        {
            List<IWebSocketConnection> sockets = new List<IWebSocketConnection>();
            Fleck.WebSocketServer server = new Fleck.WebSocketServer("ws://127.0.0.1:8181");

            server.Start(socket =>
                {
                    socket.OnOpen = () =>
                        {
                            Console.WriteLine("Connection open.");
                            sockets.Add(socket);
                        };
                    socket.OnClose = () =>
                        {
                            Console.WriteLine("Connection closed.");
                            sockets.Remove(socket);
                        };
                    socket.OnMessage = message =>
                        {
                            Console.WriteLine("Client says: " + message);
                            sockets.ToList().ForEach(s => s.Send(" client says:" + message));
                        };

                });

            string input = Console.ReadLine();
            while (input != "exit")
            {
                sockets.ToList().ForEach(s => s.Send(input));
                input = Console.ReadLine();
            }
        }
        public void Init(string port)
        {
            FleckLog.Level = LogLevel.Warn;
            _allSockets = new List<IWebSocketConnection>();
            var websocketaddr = "ws://127.0.0.1:" + port;
            Logger.WriteMinorEvent("Attempting to open a WebSocketServer on " + websocketaddr);
            _server = new WebSocketServer(websocketaddr);

            try
            {
                _server.Start(socket =>
                {
                    socket.OnOpen = () =>
                    {
                        Debug.WriteLine("Backend received an request to open a BloomWebSocketServer socket");
                        _allSockets.Add(socket);
                    };
                    socket.OnClose = () =>
                    {
                        Debug.WriteLine("Backend received an request to close  BloomWebSocketServer socket");
                        _allSockets.Remove(socket);
                    };
                });
            }
            catch (SocketException ex)
            {
                Logger.WriteEvent("Opening a WebSocketServer on " + websocketaddr + " failed.  Error = " + ex);
                ErrorReport.NotifyUserOfProblem(ex, "Bloom cannot start properly (cannot set up some internal communications){0}{0}" +
                    "What caused this?{0}" +
                    "Possibly another version of Bloom is running, perhaps not very obviously.{0}{0}" +
                    "What can you do?{0}" +
                    "Click OK, then exit Bloom and restart your computer.{0}" +
                    "If the problem keeps happening, click 'Details' and report the problem to the developers.", Environment.NewLine);
            }
        }
Пример #22
0
        public Connec()
        {
            asdassd.Add("MenuGetir", Getir);

            Method_Call M = new Method_Call();
            //Type Ty = Type.GetType("InanYalcin_FleckSoket.Model.Site." + message, true);
            //var b = Ty;
            //var Deger = M.Method(Ty,message );

            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://localhost:8181/consoleappsample");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    //var c = System.Activator.CreateInstance(Type.GetType("InanYalcin_FleckSoket.Model.Site." + message));
                    var c = asdassd[message]();
                    socket.Send(JsonConvert.SerializeObject(c, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
                    //allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                };
            });
        }
Пример #23
0
 private APIServer() 
 {
     stopwatchOffset = 0;
     trackTime = new Stopwatch();
     ip = getIpAddress();
     server = new WebSocketServer("ws://" + ip + ":" + API_PORT);
 }
Пример #24
0
        static void Main(string[] args)
        {
            string url = args.Length > 0 ? args[0] : "ws://localhost:8181";

            server = new WebSocketServer(url);

            server.Start(socket =>
            {
                socket.OnOpen = () => Open(socket);
                socket.OnClose = () => Close(socket);
                socket.OnMessage = message => Receive(socket, message);
            });

            Console.WriteLine("Type a message to send to the client (type 'exit' to close):");

            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (IWebSocketConnection socket in allSockets)
                {
                    //standard socket raw send method
                    socket.Send(input);

                    //find our dynamic sockpuppet for this socket, and call a dynamic method
                    clientDynamicWindows[socket.ConnectionInfo.Id].document.write("called from a dynamic object method: " + input);

                    //find our strongly typed interface sockpuppet for this socket, and call a typed method (that matches a method for our chosen context on the client)\
                    clientWindows[socket.ConnectionInfo.Id].alert("called from an interface method: " + input);
                }

                input = Console.ReadLine();
            }
        }
 public void Dispose()
 {
     if (_server != null)
     {
         _server.Dispose();
         _server = null;
     }
 }
Пример #26
0
 public void StartServer()
 {
     var server = new WebSocketServer("ws://localhost:10000");
     server.Start(ws =>
                      {
                          ws.OnOpen = () => OnOpenConnection(ws);
                  	});
 }
Пример #27
0
 /// <summary>
 /// Creates a WebSocket Server given location and Client Handler Type
 /// </summary>
 /// <param name="location">Location where to run the Server</param>
 /// <param name="clientHandlerType">Client Handler Type which is the Object that will be created every new Connection</param>
 public WebSocketServer(string location, Type clientHandlerType)
 {
     //Create Server
     this.Server = new Fleck.WebSocketServer(location);
     //Store Type
     this._clientHandlerType = clientHandlerType;
     //Start
     this.Server.Start(this.InitlializeSocket);
 }
Пример #28
0
        public SocketServer()
        {
            FleckLog.LogAction = (level, message, ex) => {
                if (ex != null)
                {
                    message += ex.ToString();
                }
                switch (level)
                {
                case LogLevel.Debug:
                    //Logger.log(13, Category.SocketServer, Severity.Debug, message);
                    break;

                case LogLevel.Error:
                    Logger.log(14, Category.SocketServer, Severity.Error, message);
                    break;

                case LogLevel.Warn:
                    Logger.log(15, Category.SocketServer, Severity.Warn, message);
                    break;

                default:
                    Logger.log(16, Category.SocketServer, Severity.Info, message);
                    break;
                }
            };

            Fleck.WebSocketServer server = new Fleck.WebSocketServer(Settings.socketServerUrl);
            server.Start(socket => {
                var playerWebSocket = new PlayerWebsocket(socket);
                socket.OnOpen       = () => {
                    if (playerWebSocket.isAuthenticated)
                    {
                        PlayerWebsocketConnections.AddSocket(playerWebSocket);
                    }
                    else
                    {
                        playerWebSocket.Close();
                    }
                };
                socket.OnClose = () => {
                    if (playerWebSocket.isAuthenticated)
                    {
                        PlayerWebsocketConnections.RemoveSocket(playerWebSocket);
                    }
                };
                socket.OnMessage = message => {
                    if (playerWebSocket.isAuthenticated)
                    {
                        Router.Route(playerWebSocket, message);
                    }
                };
            });


            this.server = server;
        }
Пример #29
0
        public void Initialize()
        {
            _server = new WebSocketServer(_port, "ws://localhost:" + _port + "/");

            // Nagle is a good algorithm, but not for games. Disable it.
            _server.ListenerSocket.NoDelay = true;

            _server.Start(OnConfig);
        }
Пример #30
0
        public IActionResult server()
        {
            //websocket
            string ipAddress = string.Empty;
            var    host      = System.Net.Dns.GetHostEntry(Dns.GetHostName());

            List <IWebSocketConnection> sockets = new List <IWebSocketConnection>();

            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    ipAddress = ip.ToString();
                    break;
                }
            }
            //string ipadd = "wss://panshubeinewfleck.azurewebsites.net";
            //ipadd = "ws://" + ipAddress + ":80";
            Fleck.WebSocketServer server = new Fleck.WebSocketServer("wss://" + ipAddress + ":8088");
            //Fleck.WebSocketServer server = new Fleck.WebSocketServer(ipadd);
            string path    = System.Environment.CurrentDirectory;
            bool   isexist = System.IO.File.Exists(path + "//panshubeiclub.pfx");

            if (isexist)
            {
                server.Certificate = new X509Certificate2(path + "//panshubeiclub.pfx", "panshubei");
            }
            //server.Certificate = new X509Certificate2(path+"//panshubei.club.pfx", "panshubei");
            try
            {
                server.Start(socket =>
                {
                    Trace.WriteLine("FleckSocket=>server.start");
                    socket.OnOpen = () =>
                    {
                        Trace.WriteLine("FleckSocket=>server.open");
                        sockets.Add(socket);
                    };
                    socket.OnClose = () =>
                    {
                        Trace.WriteLine("FleckSocket=>server.close");
                        sockets.Remove(socket);
                    };
                    socket.OnMessage = message =>
                    {
                        Trace.WriteLine("FleckSocket=>server.message and the message is : " + message);
                        sockets.ToList().ForEach(s => s.Send(" client says: " + message));
                    };
                });
            }
            catch (Exception ex)
            {
                Trace.WriteLine("FleckSocket=>err" + ex.ToString());
                throw;
            }
            return(View());
        }
Пример #31
0
        private static void InitializeSockets()
        {
            _sockets = new List<IWebSocketConnection>();

            var server = new WebSocketServer("ws://localhost:8181");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Connected to " + socket.ConnectionInfo.ClientIpAddress);
                    _sockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    if(socket.ConnectionInfo != null)
                        Console.WriteLine("Disconnected from " + socket.ConnectionInfo.ClientIpAddress);
                    _sockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    if (message.StartsWith("setSensorRange("))
                    {
                        /*
                        int parameterLength = message.IndexOf(")") - message.IndexOf("(") -1; // either 1 or 2
                        string numberParameter = message.Substring("setSensorRange(".Length, parameterLength);

                        try
                        {
                            int number = int.Parse(numberParameter);
                            if (-27 < number && number < 27)
                            {
                                _sensor.ElevationAngle = 5;
                            }
                            else
                            {
                                Console.WriteLine("invalid value. must be between -27 and 27 degrees");
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Error converting number parameter " + numberParameter + " to int. paramLength = " + parameterLength + "; stacktrace: ");
                            Console.WriteLine(e.StackTrace);
                        }
                         */
                    }
                };
            });

            _initialized = true;
            Console.WriteLine(" done.");
            Console.WriteLine("");

            Console.ReadLine();
        }
Пример #32
0
        /// <summary>
        /// Stop the server listening.
        /// </summary>
        public void Stop()
        {
            // Kill the server.
            if (Server != null)
                Server.Dispose();
            Server = null;

            // Update flags.
            Running = false;
        }
Пример #33
0
        /// <summary>
        /// Start the server listening.
        /// </summary>
        /// <param name="sHostURI"></param>
        public void Start(String sHostURI)
        {
            // Stop it.
            Stop();

            // Start the server listening on the port specified by args.
            Server = new WebSocketServer(sHostURI);
            Server.Start(OnClient);
            Running = true;
        }
Пример #34
0
 public void Start()
 {
     WebSocketServer = new Fleck.WebSocketServer(URL);
     WebSocketServer.Start(socket =>
     {
         socket.OnOpen    = () => OnOpen(socket);
         socket.OnClose   = () => OnClose(socket);
         socket.OnMessage = m => OnMessage(socket, m);
     });
 }
Пример #35
0
        private void Window_Initialized(object sender, System.EventArgs e)
        {
            http = new HttpServer();

            // TODO: Allow user to change the port
            webSocketServer = new WebSocketServer("ws://0.0.0.0:8958");
            webSockets = new List<IWebSocketConnection>();

            UpdateStatus();
        }
Пример #36
0
 public Communication(Action connectCallback, Action<string[]> messageCallback)
 {
     Server = new WebSocketServer("ws://0.0.0.0:11650/socket");
     Server.Start(socket =>
     {
         socket.OnOpen = () => SetSocket(socket, connectCallback);
         socket.OnClose = () => Connected = false;
         socket.OnMessage = message => messageCallback(Split(message));
     });
 }
Пример #37
0
        public void FeatureParityTest()
        {
            using (var server = new WebSocketServer("http://127.0.0.1:8989"))
            {
                server.Start(ConfigureIntegrationTestConnection);
                SendIntegrationTestMessages();
            }

            AssertIntegrationTestMessages();
        }
Пример #38
0
 public void StartServer()
 {
     var server = new WebSocketServer("ws://localhost:8080");
     server.Start(socket =>
     {
         socket.OnOpen = () => { Connections.Add(socket); socket.Send(Serializer.Rewind()); };
         socket.OnClose = () => Connections.Remove(socket);
         socket.OnMessage = (string m) => OnMessage(socket, m);
     });
 }
Пример #39
0
        public void Stop()
        {
            Logger.Instance().InfoWithFormat(" >> Stop Web Socket Server {0}.", _server.Location);

            RequestManager.Instance().Stop();

            if (_server != null)
            {
                _server.Dispose();
                _server = null;
            }
        }
Пример #40
0
        /// <summary>
        /// Start web socket server.
        /// </summary>
        private void StartWebSocketServer()
        {
            // stop web socket server in case a server is already running.
            StopWebSocketServer();

            _limitFpsStopwatch.Start();

            _webSocketServer = new Fleck.WebSocketServer(string.Format("ws://0.0.0.0:{0}", Port));
            _webSocketServer.Start(socket =>
            {
                socket.OnOpen    = () => OnClientConnect(socket);
                socket.OnClose   = () => OnClientDisconnect(socket);
                socket.OnMessage = message => OnClientMessage(socket, message);
            });
        }
Пример #41
0
 WebSocketTest()
 {
     server = new Fleck.WebSocketServer("ws://localhost:8123");
     //something.
     server.Start(socket =>
     {
         socket.OnOpen    = () => allSockets.Add(socket);
         socket.OnClose   = () => allSockets.Remove(socket);
         socket.OnMessage = message =>
         {
             foreach (var s in allSockets)
             {
                 s.Send(message);
             }
         };
     });
 }
Пример #42
0
        public OverlayServer(OverlayServerConfig config)
        {
            this.config = config;

            try
            {
                var WSS = new Fleck.WebSocketServer($"ws://127.0.0.1:{config.Port}");
                // Set the websocket listeners
                WSS.Start(connection =>
                {
                    connection.OnOpen  += () => OnWsConnectionOpen(connection);
                    connection.OnClose += () => OnWSConnectionClose(connection);
                });
            } catch (Exception e)
            {
                logger.Fatal(e, "failed so start websocket server");
            }
        }
Пример #43
0
        public void Start()
        {
            FleckLog.Level = LogLevel.Debug;

            if (_server == null)
            {
                Logger.Instance().Info(" >> Starting Web Socket Server...");

                // start request manager
                //
                RequestManager.Instance().Start();

                var serverLocation = string.Format("ws://localhost:{0}", 8181);
                _server = new Fleck.WebSocketServer(serverLocation);
                _server.Start(ServerConfig);

                Logger.Instance().InfoWithFormat(" >> Running Web Socket Server {0}.", _server.Location);
            }
        }
Пример #44
0
        /// <summary>
        /// Main entry point.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            ParseCliParameters(ref args);

            var host      = Dns.GetHostEntry(Dns.GetHostName());
            var ipAddress = "127.0.0.1";

            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    ipAddress = ip.ToString();
                    break;
                }
            }

            var webSocketServer = new Fleck.WebSocketServer($"ws://{ipAddress}:{ServerPort}");

            webSocketServer.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine($"Connection Opened by {socket.ConnectionInfo.ClientIpAddress}.");
                    clients.Add(socket);
                    countClients++;
                };

                socket.OnClose = () =>
                {
                    Console.WriteLine($"Connection Closed by {socket.ConnectionInfo.ClientIpAddress}.");
                    clients.Remove(socket);
                    countClients--;
                };
            });

            Console.WriteLine("WebSocket Server Started!");

            StartArduino();

            Console.ReadKey();
        }
Пример #45
0
        /// <summary>
        /// Entry point for the application.
        /// </summary>
        /// <param name="args">
        /// Command-line arguments for this console application are as follows:
        ///
        /// Param 1: Server name. Cannot contain spaces. Valid characters are A-Z, a-z, 0-9, _, -, and .
        /// Param 2: Port number. Must be between 1000 and 65535.
        /// Param 3: Admin password. Cannot contain spaces.
        ///
        /// A sample run might look like this, if invoked manually: C:\> PokerServer.exe MyName 8500 MyPass
        /// </param>
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                ExitWithError("Invalid number of command-line arguments (Password can not contain spaces).");
            }

            int portNumber;

            if (!int.TryParse(args[1], out portNumber))
            {
                ExitWithError("Port number is invalid.");
            }
            if (portNumber < 1000 || portNumber > 65535)
            {
                ExitWithError("Port number is outside valid range [1000-65535].");
            }
            if (!Regex.IsMatch(args[0], @"^[a-zA-Z0-9_\-.]+$"))
            {
                ExitWithError("Name is invalid. Valid name characters are A-Z, a-z, 0-9, _, -, and .");
            }

            Name = args[0];
            Port = portNumber;

            // Set up the named pipe server and the initial async connection listener.
            NamedPipeServerStream nps = new NamedPipeServerStream("wss" + Process.GetCurrentProcess().Id, PipeDirection.Out, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

            nps.BeginWaitForConnection(PipeHandler, nps);

            cs = new CardServer(args[2]);

            server = new Fleck.WebSocketServer("ws://" + Environment.MachineName + ":" + Port + "/");
            server.Start(s => cs.NewClient((WebSocketConnection)s));

            while (true)
            {
                Console.ReadKey();
            }
        }
Пример #46
0
        public WebSocketServer(string ip, int port, Action <string, Log.LogLevel> logDelegate)
        {
            GetPhysicallyInstalledSystemMemory(out memorySize);

            FleckLog.Level = LogLevel.Error + 1;
            Fleck.WebSocketServer server = new Fleck.WebSocketServer($"ws://{ip}:{port}");
            this.logDelegate = logDelegate;
            server.Start(serverConnected);

            try {
                IISManager.GetSites().ForEach(info => {
                    siteCurrentConnections.Add(new PerformanceCounter("Web Service", "Current Connections", info.Name));
                });
            }
            catch { }


            Timer timer = new Timer(1000);

            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }
Пример #47
0
        public void Initialize()
        {
            string location = TTSettings.GetAppSetting <string>("hostingUrl", defaultVal: "ws://0.0.0.0:8082");

            _server = new Fleck.WebSocketServer(location);

            _server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    var clientInfo = new ClientInfo(socket.ConnectionInfo.Id, socket);
                    ClientInfo.TryAdd(socket.ConnectionInfo.Id, clientInfo);

                    var logMessage = "New client connected successfully. id = " + clientInfo.ConnectionGuid;
                    Logger.Current.Info(logMessage);


                    NotifySubscriber(_previousQuotes, clientInfo);
                };

                socket.OnError = OnError;

                socket.OnClose = () =>
                {
                    var found = ClientInfo.FirstOrDefault(ci => ci.Key == socket.ConnectionInfo.Id).Value;
                    if (found != null)
                    {
                        ClientInfo.TryRemove(socket.ConnectionInfo.Id, out found);
                        var logMessage = "Client disconnected. id = " + found.ConnectionGuid;
                        Logger.Current.Info(logMessage);
                    }
                };

                socket.OnMessage = message => OnMessageFromClient(message, socket);
            });
        }
Пример #48
0
        /// <summary>
        /// Starts the server.
        /// </summary>
        public async Task <IWebSocketServer> Start()
        {
            Logger?.Log(LogLevel.Debug, $"Starting server at '{this.Location}'");

            string alreadyStartedMessage = $"Server at '{this.Location}' is already running";

            // Check if the server is already running
            if (this.IsRunning)
            {
                Logger?.Log(LogLevel.Debug, alreadyStartedMessage);

                // Return this object so calls can be chained
                return(this);
            }

            // Start the server in a new thread
            return(await Task.Run <IWebSocketServer>(() =>
            {
                lock (this._lock)
                {
                    // Check again if the server is already running in case it was started before reaching the lock statement
                    if (this.IsRunning)
                    {
                        Logger?.Log(LogLevel.Debug, alreadyStartedMessage);
                        return this;
                    }

                    // Try to start the server
                    try
                    {
                        // Create a new instance of the server
                        this._server = new FleckImpl.WebSocketServer(this.Location);

                        // Set the cert if required
                        if (this.Certificate != null)
                        {
                            this._server.Certificate = this.Certificate;
                        }

                        // Start the server
                        this._server.Start(FleckServiceConfig);
                        Logger?.Log(LogLevel.Warning, $"Started server at '{this.Location}'");
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            this._server.Dispose();
                        }
                        finally
                        {
                            this._server = null;
                            Logger?.Log(LogLevel.Error, $"Failed to start server at '{this.Location}'", ex);
                        }
                    }

                    // Return this object so calls can be chained
                    return this;
                }
            }));
        }
Пример #49
0
 /// <summary>
 /// Instantiates a websocket server
 /// </summary>
 /// <param name="port">The port</param>
 public WebsocketServer(int port)
 {
     _port   = port;
     _server = new Fleck.WebSocketServer("ws://localhost:" + port.ToString());
 }
        static void Main(string[] args)
        {
            _allSockets = new List <IWebSocketConnection>();
            _allMeans   = new Dictionary <string, decimal>();
            _allCounts  = new Dictionary <string, decimal>();

            var serverAddresses = new Dictionary <string, string>();

            //serverAddresses.Add("USA-WestCoast", "ws://127.0.0.1:58951");
            //serverAddresses.Add("USA-EastCoast", "ws://127.0.0.1:58952");
            serverAddresses.Add("UK", "ws://127.0.0.1:58953");
            serverAddresses.Add("EU-North", "ws://127.0.0.1:58954");
            //serverAddresses.Add("EU-South", "ws://127.0.0.1:58955");
            foreach (var serverAddress in serverAddresses)
            {
                _allMeans.Add(serverAddress.Key, 0m);
                _allCounts.Add(serverAddress.Key, 0m);
            }

            var thisNodeName        = ConfigurationSettings.AppSettings["thisNodeName"];        //for example "UK"
            var serverSocketAddress = serverAddresses.First(x => x.Key == thisNodeName);

            serverAddresses.Remove(thisNodeName);

            var websocketServer = new Fleck.WebSocketServer(serverSocketAddress.Value);

            websocketServer.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    _allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    _allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message + " received");

                    var parameters         = message.Split('~');
                    var remoteHost         = parameters[0];
                    var remoteMean         = decimal.Parse(parameters[1]);
                    var remoteCount        = decimal.Parse(parameters[2]);
                    _allMeans[remoteHost]  = remoteMean;
                    _allCounts[remoteHost] = remoteCount;
                };
            });
            while (true)
            {
                //evaluate my local average and count
                Random rand = new Random(DateTime.Now.Millisecond);
                _localMean  = 234.00m + (rand.Next(0, 100) - 50) / 10.0m;
                _localCount = 222m + rand.Next(0, 100);

                //evaluate my local aggregate average using means and counts sent from all other nodes
                //could publish aggregate averages to other nodes, if you wanted to monitor disagreement between nodes
                var total_mean_times_count = 0m;
                var total_count            = 0m;
                foreach (var server in serverAddresses)
                {
                    total_mean_times_count += _allCounts[server.Key] * _allMeans[server.Key];
                    total_count            += _allCounts[server.Key];
                }
                //add on local mean and count which were removed from the server list earlier, so won't be processed
                total_mean_times_count += (_localMean * _localCount);
                total_count             = total_count + _localCount;

                _localAggregate_average = (total_mean_times_count / total_count);
                _localAggregate_count   = total_count;

                Console.WriteLine("local aggregate average = {0}", _localAggregate_average);

                System.Threading.Thread.Sleep(10000);
                foreach (var serverAddress in serverAddresses)
                {
                    using (var wscli = new ClientWebSocket())
                    {
                        var tokSrc = new CancellationTokenSource();
                        using (var task = wscli.ConnectAsync(new Uri(serverAddress.Value), tokSrc.Token))
                        {
                            task.Wait();
                        }

                        using (var task = wscli.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(thisNodeName + "~" + _localMean + "~" + _localCount)),
                                                          WebSocketMessageType.Text,
                                                          false,
                                                          tokSrc.Token
                                                          ))
                        {
                            task.Wait();
                        }
                    }
                }
            }
        }
Пример #51
0
        static void Main(string[] args)
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());
            container.Install(FromAssembly.Named("Router"));
            container.Install(FromAssembly.Named("Repository"));
            //container.Install(FromAssembly.Named("Mapper"));

            //container.Register(Castle.MicroKernel.Registration.Component.For<Router.Router>().ImplementedBy<Router.Router>());
            //container.Register(Castle.MicroKernel.Registration.Component.For<Router.Styler>().ImplementedBy<Router.Styler>());
            //container.Register(Castle.MicroKernel.Registration.Component.For<Router.IStyler>().ImplementedBy<Router.IStyler>());
            //container.Register(Castle.MicroKernel.Registration.Component.For<Repository.MapRepo>().ImplementedBy<Repository.MapRepo>());

            var router = container.Resolve <Router.Router>();

            //    private readonly IRepository<State> _stateRepo;
            //private readonly IRepository<Connection> _connectionRepo;
            //private readonly IRepository<User> _userRepo;
            //private readonly IRepository<NavCategory> _navCategoryRepo;
            //private readonly IRepository<StatusBarItem> _statusBarRepo;
            //private readonly IRepository<Subscription> _subscriptionRepository;
            //private readonly IStyler _styler;


            _allSockets = new List <IWebSocketConnection>();
            var websocketServer = new Fleck.WebSocketServer("ws://127.0.0.1:58951");

            websocketServer.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    CreateConnection(socket);
                    _allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    DeleteConnection(socket);
                    _allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    switch (message)
                    {
                    case "seed":
                        var initializer = container.Resolve <Repository.SockMinInitializer>();
                        var context     = container.Resolve <Repository.SockMinDbContext>();
                        initializer.Seed(context);
                        break;

                    case "query1":
                        socket.Send(@"content~<table><tr><td>Name</td><td>Address</td><td>Phone</td></tr>
                                    <tr><td>Jeff</td><td>the place</td><td>234234</td></tr></table>");
                        Console.WriteLine(message + " received");
                        break;

                    case "query2":
                        socket.Send(@"content~<table><tr><td>Year</td><td>Quarter</td><td>Sales(£k)</td></tr>
                                    <tr><td>2016</td><td>Q1</td><td>437</td></tr></table>");
                        Console.WriteLine(message + " received");
                        break;

                    case "query3":
                        socket.Send(@"content~<table><tr><td>Computer</td><td>Software</td><td>Version</td></tr>
                                    <tr><td>TG-IIS01</td><td>Amadeus</td><td>1.2.3</td></tr></table>");
                        Console.WriteLine(message + " received");
                        break;

                    case "query4":
                        socket.Send(@"content~
<svg class='chart' width='420' height='150' aria-labelledby='title desc' role='img'>
  <title id = 'title'> A bar chart showing information </title>
  <desc id = 'desc'> 4 apples; 8 bananas; 15 kiwis; 16 oranges; 23 lemons </desc>
     
       <g class='bar'>
    <rect width = '40' height='19'></rect>
    <text x = '45' y='9.5' dy='.35em'>4 apples</text>
  </g>
  <g class='bar'>
    <rect width = '80' height='19' y='20'></rect>
    <text x = '85' y='28' dy='.35em'>8 bananas</text>
  </g>
  <g class='bar'>
    <rect width = '150' height='19' y='40'></rect>
    <text x = '150' y='48' dy='.35em'>15 kiwis</text>
  </g>
  <g class='bar'>
    <rect width = '160' height='19' y='60'></rect>
    <text x = '161' y='68' dy='.35em'>16 oranges</text>
  </g>
  <g class='bar'>
    <rect width = '230' height='19' y='80'></rect>
    <text x = '235' y='88' dy='.35em'>23 lemons</text>
  </g>
</svg>");
                        Console.WriteLine(message + " received");
                        break;

                    case "query5":
                        socket.Send(@"content~<table><tr><td>Computer</td><td>Software</td><td>Version</td></tr>
                                    <tr><td>TG-IIS01</td><td>Amadeus</td><td>1.2.3</td></tr></table>");
                        Console.WriteLine(message + " received");
                        break;

                    default:
                        var command = message.Split(':');
                        switch (command[0])
                        {
                        case "updateState":
                            router.ChangeConnectionState(socket, command[1]);
                            break;

                        default:
                            break;
                        }
                        socket.Send("messages~" + message + " received");
                        Console.WriteLine(message + " received");
                        break;
                    }
                };
            });
            while (true)
            {
                System.Threading.Thread.Sleep(10000);
                foreach (var socket in _allSockets.ToList())
                {
                    socket.Send("status~" + DateTime.UtcNow.ToString("o") + " all is well on connection " + socket.ConnectionInfo.Id);
                }
            }
        }
Пример #52
0
 public void Start()
 {
     _server = new WebSocketServer(GetUrl());
     _server.Start(MessageReceived);
 }
Пример #53
0
        /// <summary>
        /// Entry point for the application.
        /// </summary>
        /// <param name="args">
        /// Command-line arguments for this console application are as follows:
        ///
        /// Param 1: Server name. Cannot contain spaces. Valid characters are A-Z, a-z, 0-9, _, -, and .
        /// Param 2: Port number. Must be between 1000 and 65535.
        /// Param 3: Admin password. Cannot contain spaces.
        ///
        /// A sample run might look like this, if invoked manually: C:\> PokerServer.exe MyName 8500 MyPass
        /// </param>
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                args    = new string[4];
                args[0] = "FC";
                args[1] = "8000";
                args[2] = "abcd";
                args[3] = "127.0.0.1";

                Console.WriteLine("Enter Room Name:");
                args[0] = Console.ReadLine();
                Console.WriteLine("Enter Port No Bet 8000 & 9000:");
                args[1] = Console.ReadLine();
                Console.WriteLine("Enter Room Password:"******"Enter Hosting IP or D for auto detect:");
                args[3] = Console.ReadLine();
            }

            int portNumber;

            if (!int.TryParse(args[1], out portNumber))
            {
                ExitWithError("Port number is invalid.");
            }
            if (portNumber < 1000 || portNumber > 65535)
            {
                ExitWithError("Port number is outside valid range [1000-65535].");
            }
            if (!Regex.IsMatch(args[0], @"^[a-zA-Z0-9_\-.]+$"))
            {
                ExitWithError("Name is invalid. Valid name characters are A-Z, a-z, 0-9, _, -, and .");
            }

            Name = args[0];
            Port = portNumber;
            if (args[3].Equals("D"))
            {
                if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    throw new Exception("Network not available.");
                }

                IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

                MachineIp = host
                            .AddressList
                            .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();
            }
            else
            {
                MachineIp = args[3];
            }

            // Set up the named pipe server and the initial async connection listener.
            NamedPipeServerStream nps = new NamedPipeServerStream("wss" + Process.GetCurrentProcess().Id, PipeDirection.Out, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

            nps.BeginWaitForConnection(PipeHandler, nps);

            cs = new CardServer(args[2]);

            try
            {
                //server = new Fleck.WebSocketServer("ws://" + Environment.MachineName + ":" + Port + "/");
                server = new Fleck.WebSocketServer("ws://" + MachineIp + ":" + Port + "/");
                server.Start(s => cs.NewClient((WebSocketConnection)s));
                Console.WriteLine("PID: " + Process.GetCurrentProcess().Id);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
            }

            while (true)
            {
                Console.ReadKey();
            }
        }
Пример #54
0
        public static void Init(string url)
        {
            if (socket == null)
            {
                socket = new Fleck.WebSocketServer(url);
                socket.RestartAfterListenError = true;

                FleckLog.LogAction = (level, message, ex) =>
                {
                    switch (level)
                    {
                    case LogLevel.Debug:
                        logger.Debug("WebSocket -> " + message, ex);
                        break;

                    case LogLevel.Error:
                        logger.Error("WebSocket -> " + message, ex);
                        break;

                    case LogLevel.Warn:
                        logger.Warn("WebSocket -> " + message, ex);
                        break;

                    default:
                        logger.Info("WebSocket -> " + message, ex);
                        break;
                    }
                };

                socket.Start(conn =>
                {
                    conn.OnOpen = () =>
                    {
                        if (connections.FirstOrDefault(x => x.ConnectionInfo.Id == conn.ConnectionInfo.Id) == null)
                        {
                            connections.Add(conn);
                        }
                        logger.Info("WebSocket -> new connection from: " + conn.ConnectionInfo.ClientIpAddress + " with GUID: " + conn.ConnectionInfo.Id);
                    };

                    conn.OnMessage = message =>
                    {
                        logger.Info("WebSocket -> Message received from: " + conn.ConnectionInfo.ClientIpAddress + " with GUID: " + conn.ConnectionInfo.Id);
                        WebSocketServer.SendMessage(message, conn.ConnectionInfo.Id);
                    };

                    conn.OnClose = () =>
                    {
                        connections.Remove(connections.First(x => x.ConnectionInfo.Id == conn.ConnectionInfo.Id));
                        logger.Info("WebSocket -> close connection from: " + conn.ConnectionInfo.ClientIpAddress + " with GUID: " + conn.ConnectionInfo.Id);
                    };

                    conn.OnBinary = binary =>
                    {
                        WebSocketServer.SendMessage(Encoding.UTF8.GetString(binary), conn.ConnectionInfo.Id);
                    };

                    conn.OnError = error =>
                    {
                        logger.Error("WebSocket -> Error with connection: " + conn.ConnectionInfo.ClientIpAddress + " and GUID: " + conn.ConnectionInfo.Id, error);
                    };
                });
                logger.Info("WebSocket server initialized for url: " + url);
            }
        }
Пример #55
0
        static void Main(string[] args)
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List <SocketInfo>();
            var server     = new Fleck.WebSocketServer("ws://0.0.0.0:9146");

            //var x = new Fleck.websocketc
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("连接打开!");
                    var x = allSockets.Where(i => i.ID == socket.ConnectionInfo.Id.ToString()).FirstOrDefault();
                    if (x != null)
                    {
                        return;
                    }
                    allSockets.Add(new SocketInfo()
                    {
                        ID = socket.ConnectionInfo.Id.ToString(),
                        IWebSocketConnection = socket
                    });
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("连接关闭!");
                    var x = allSockets.Where(i => i.ID == socket.ConnectionInfo.Id.ToString()).FirstOrDefault();
                    if (x != null)
                    {
                        allSockets.Remove(x);
                    }
                    foreach (var item in allSockets)
                    {
                        item.IWebSocketConnection.Send($"{x.User}下线了");
                    }
                };
                socket.OnMessage = message =>
                {
                    if (string.IsNullOrEmpty(message))
                    {
                        return;
                    }
                    var fromUser = allSockets.Where(i => i.ID == socket.ConnectionInfo.Id.ToString()).FirstOrDefault();
                    if (fromUser != null && string.IsNullOrEmpty(fromUser.User))
                    {
                        fromUser.User = message;
                        foreach (var item in allSockets)
                        {
                            item.IWebSocketConnection.Send($"{message}上线啦。");
                        }
                        return;
                    }
                    Console.WriteLine($"{socket.ConnectionInfo.Id}:{message}");
                    foreach (var item in allSockets)
                    {
                        item.IWebSocketConnection.Send($"{fromUser.User}:{message}");
                    }
                    //allSockets.Select(i=>i.IWebSocketConnection).ToList().ForEach(s => s.Send($"{s.us}:{message} "));
                };
            });


            var input = Console.ReadLine();

            while (input != "exit")
            {
                foreach (var socket in allSockets.Select(i => i.IWebSocketConnection).ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
Пример #56
0
 public SocketHelp(string location)
 {
     WebSocketServer = new Fleck.WebSocketServer(location);
 }