protected override void OnStop() { this._isPaused = false; if (this._server != null) { foreach (Fleck.IWebSocketConnection client in this._connections) { if (client != null && client.IsAvailable == true) { client.Close(); } } this._server.Dispose(); this._server = null; } if (this._connections != null) { this._connections.Clear(); } this._connections = null; if (this._eventLog != null) { this._eventLog.Dispose(); } }
public void Start() { List <Fleck.IWebSocketConnection> sockets = new List <Fleck.IWebSocketConnection>(); var 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 Start(string connectionStr) { server = new Fleck.WebSocketServer(connectionStr); server.Start(socket => { socket.OnOpen = () => { AsyncTaskQueue.Instance.AddAsyncAction( () => { OnOpen(socket); } ); }; socket.OnClose = () => { AsyncTaskQueue.Instance.AddAsyncAction(() => { OnClose(socket); }); }; socket.OnMessage = (message) => { AsyncTaskQueue.Instance.AddAsyncAction(() => { OnMessage(socket, message); }); }; }); }
//readonly string Email = "*****@*****.**"; //readonly string Password = "******"; //readonly string BotToken = "MTkyNjI4NzY5ODMwMjA3NDg5.CkLnBQ.ZvmlN4E2koYhcOOKX5z2wYOrmcE"; static void Main(string[] args) { var websocketServet = new Fleck.WebSocketServer("ws://0.0.0.0"); websocketServet.Start(socket => { socket.OnOpen = () => Console.WriteLine("WebSocket Open"); socket.OnClose = () => Console.WriteLine("WebSocket Closed"); }); KWRBot bot = new KWRBot(); bot.Login(); Console.ReadKey(); bot.Exit(); }
private void StartWebSocketChatServer() { var _connections = new List<Fleck.IWebSocketConnection>(); _server = new Fleck.WebSocketServer("ws://*****:*****@"logs\websocketerror.txt"); var data = DateTime.Now + Environment.NewLine + ex.ToString() + Environment.NewLine; lock (_websocketErrorLogLock) { Directory.CreateDirectory(Path.GetDirectoryName(path)); File.AppendAllText(path, data); } }; socket.OnOpen = () => { _connections.Add(socket); }; socket.OnClose = () => { _connections.Add(socket); }; socket.OnMessage = (msg) => { foreach (var s in _connections) { s.Send(msg); } }; }); }
protected override void OnStart(string[] args) { this._connections.Clear(); this._isPaused = false; Int32 port; if (System.Int32.TryParse(System.Configuration.ConfigurationSettings.AppSettings["Port"], out port) == false) { port = 8181; } Fleck.FleckLog.Level = Fleck.LogLevel.Error; if (System.Diagnostics.EventLog.SourceExists(this.ServiceName) == true) { this._eventLog.WriteEntry("SocketService is listening to port " + port, EventLogEntryType.Information); } this._server = new Fleck.WebSocketServer(port, "ws://localhost/"); this._server.Start(socket => { socket.OnOpen = () => { if (System.Diagnostics.EventLog.SourceExists(this.ServiceName) == true) { this._eventLog.WriteEntry("Client '" + socket.ConnectionInfo.Host + "' connected (" + socket.ConnectionInfo.Id + ", '" + socket.ConnectionInfo.Path + "').", EventLogEntryType.Information); } this._connections.Add(socket); }; socket.OnClose = () => { if (System.Diagnostics.EventLog.SourceExists(this.ServiceName) == true) { this._eventLog.WriteEntry("Client '" + socket.ConnectionInfo.Host + "' disconnected (" + socket.ConnectionInfo.Id + ").", EventLogEntryType.Information); } this._connections.Remove(socket); }; socket.OnError = exception => { if (exception is System.IO.IOException) { if (System.Diagnostics.EventLog.SourceExists(this.ServiceName) == true) { this._eventLog.WriteEntry("Client '" + socket.ConnectionInfo.Host + "' disconnected with an abnormal behaviour (" + socket.ConnectionInfo.Id + ").", EventLogEntryType.Information); } } else { if (System.Diagnostics.EventLog.SourceExists(this.ServiceName) == true) { this.EventLog.WriteEntry(exception.GetType().ToString() + "\n" + exception.Message + "\n\n" + exception.StackTrace, EventLogEntryType.Error); } } }; socket.OnMessage = message => { if (this._isPaused == true) { return; } this._broadcastBuffer.Enqueue(new BufferItem(socket.ConnectionInfo.Id, message)); if (System.Threading.Monitor.IsEntered(SocketService._broadcastLock) == false) //this._isThreading == false { (new System.Threading.Thread(this.BroadcastMessage)).Start(); } }; }); }
public void Start(string[] args) { // prepare this.IsUserInteractive = Environment.UserInteractive && args?.FirstOrDefault(a => a.StartsWith("/daemon")) == null; if (string.IsNullOrWhiteSpace(this.Address) || string.IsNullOrWhiteSpace(this.Realm)) { this.Address = args?.FirstOrDefault(a => a.StartsWith("/address:")); if (string.IsNullOrWhiteSpace(this.Address)) { this.Address = ConfigurationManager.AppSettings["Address"]; } else { this.Address = this.Address.Substring(this.Address.IndexOf(":") + 1).Trim(); } if (string.IsNullOrWhiteSpace(this.Address)) { this.Address = "ws://0.0.0.0:16429/"; } else if (!this.Address.EndsWith("/")) { this.Address += "/"; } this.Realm = args?.FirstOrDefault(a => a.StartsWith("/realm:")); if (string.IsNullOrWhiteSpace(this.Realm)) { this.Realm = ConfigurationManager.AppSettings["Realm"]; } else { this.Realm = this.Realm.Substring(this.Realm.IndexOf(":") + 1).Trim(); } if (string.IsNullOrWhiteSpace(this.Realm)) { this.Realm = "VIEAppsRealm"; } var sslCertificateFilePath = ConfigurationManager.AppSettings["SslCertificate:FilePath"]; if (!string.IsNullOrWhiteSpace(sslCertificateFilePath) && sslCertificateFilePath.EndsWith(".pfx") && File.Exists(sslCertificateFilePath)) { try { var sslCertificatePassword = ConfigurationManager.AppSettings["SslCertificate:Password"]; this.SslCertificate = sslCertificatePassword != null ? new X509Certificate2(sslCertificateFilePath, sslCertificatePassword, X509KeyStorageFlags.UserKeySet) : new X509Certificate2(sslCertificateFilePath); this.SslProtocol = Enum.TryParse(ConfigurationManager.AppSettings["SslProtocol"] ?? "Tls12", out SslProtocols sslProtocol) ? sslProtocol : SslProtocols.Tls12; } catch (Exception ex) { this.OnError?.Invoke(ex); } } } void startRouter() { try { this.Host = this.SslCertificate != null ? new DefaultWampHost(this.Address.Replace("ws://", "wss://"), null, null, null, this.SslCertificate, () => this.SslProtocol) : new DefaultWampHost(this.Address.Replace("wss://", "ws://")); this.HostedRealm = this.Host.RealmContainer.GetRealmByName(this.Realm); this.HostedRealm.SessionCreated += (sender, arguments) => { var details = arguments.HelloDetails.TransportDetails; var type = details.GetType(); var property = type.GetProperty("Peer", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); var peer = property != null && property.CanRead ? property.GetValue(details) : null; var uri = peer != null ? new Uri(peer as string) : null; property = type.GetProperty("Id", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); var id = property != null && property.CanRead ? property.GetValue(details) : null; var sessionInfo = new SessionInfo { SessionID = arguments.SessionId, ConnectionID = id != null ? (Guid)id : Guid.NewGuid(), EndPoint = new IPEndPoint(IPAddress.TryParse(uri?.Host ?? "0.0.0.0", out var ipAddress) ? ipAddress : IPAddress.Parse("0.0.0.0"), uri != null ? uri.Port : 16429) }; this.Sessions.TryAdd(arguments.SessionId, sessionInfo); this.OnSessionCreated?.Invoke(sessionInfo); }; this.HostedRealm.SessionClosed += (sender, arguments) => { if (this.Sessions.TryRemove(arguments.SessionId, out var sessionInfo)) { sessionInfo.CloseType = arguments.CloseType.ToString(); sessionInfo.CloseReason = arguments.Reason; } this.OnSessionClosed?.Invoke(sessionInfo); }; this.Host.Open(); } catch (Exception ex) { var message = $"Cannot start the router => {ex.Message}"; if (ex is SocketException && ex.Message.StartsWith("Address already in use")) { message = $"Cannot start the router (because the port is already in use by another app) => Please make sure no app use the port {new Uri(this.Address).Port}"; } this.OnError?.Invoke(new Exception(message, ex)); } } void startStatisticServer() { var address = $"{(this.SslCertificate != null ? "wss" : "ws")}://0.0.0.0:{(Int32.TryParse(ConfigurationManager.AppSettings["StatisticsWebSocketServer:Port"] ?? "56429", out var port) ? port : 56429)}/ "; try { this.StatisticsServer = new Fleck.WebSocketServer(address) { Certificate = this.SslCertificate, EnabledSslProtocols = this.SslProtocol }; this.StatisticsServer.Start(websocket => { websocket.OnMessage = message => { try { var json = JObject.Parse(message); var command = json.Value <string>("Command") ?? "Unknown"; if (command.ToLower().Equals("info")) { Task.Run(() => websocket.Send(this.RouterInfo.ToString(Formatting.None))).ConfigureAwait(false); } else if (command.ToLower().Equals("connections")) { Task.Run(() => websocket.Send(new JObject { { "Connections", this.Sessions.Count } }.ToString(Formatting.None))).ConfigureAwait(false); } else if (command.ToLower().Equals("sessions")) { Task.Run(() => websocket.Send(this.SessionsInfo.ToString(Formatting.None))).ConfigureAwait(false); } else if (command.ToLower().Equals("session")) { if (this.Sessions.TryGetValue(json.Value <long>("SessionID"), out var sessionInfo)) { Task.Run(() => websocket.Send(sessionInfo.ToJson().ToString(Formatting.None))).ConfigureAwait(false); } else { Task.Run(() => websocket.Send(new JObject { { "Error", $"Not Found" } }.ToString(Formatting.None))).ConfigureAwait(false); } } else if (command.ToLower().Equals("update")) { if (this.Sessions.TryGetValue(json.Value <long>("SessionID"), out var sessionInfo)) { sessionInfo.Name = json.Value <string>("Name"); sessionInfo.Description = json.Value <string>("Description"); } } else { Task.Run(() => websocket.Send(new JObject { { "Error", $"Unknown command [{message}]" } }.ToString(Formatting.None))).ConfigureAwait(false); } } catch (Exception ex) { Task.Run(() => websocket.Send(new JObject { { "Error", $"Bad command [{message}] => {ex.Message}" } }.ToString(Formatting.None))).ConfigureAwait(false); } }; }); } catch (Exception ex) { var message = $"Cannot start the statistics server => {ex.Message}"; if (ex is SocketException && ex.Message.StartsWith("Address already in use")) { message = $"Cannot start the statistics server (because the port is already in use by another app) => Please make sure no app use the port {new Uri(address).Port}"; } this.OnError?.Invoke(new Exception(message, ex)); this.StatisticsServer = null; } } // start startRouter(); if (this.Host != null) { if ("true".Equals(ConfigurationManager.AppSettings["StatisticsWebSocketServer:Enable"] ?? "true")) { startStatisticServer(); } this.OnStarted?.Invoke(); } }
/// <summary> /// Instantiates a websocket server /// </summary> /// <param name="hostname">The hostname</param> /// <param name="port">The port</param> public WebsocketServer(string hostname, int port) { _port = port; _server = new Fleck.WebSocketServer(port, "ws://" + hostname.ToLower()); }