//Initializes the web socket server that listens for incoming requests private static void InitializeWebSockets() { allSockets = new List <IWebSocketConnection>(); server = new WebSocketServer(WEB_SOCKET_SERVICE_URL); server.Start(socket => { socket.OnOpen = () => { Console.WriteLine("Connection Opened"); offer = null; allSockets.Add(socket); }; socket.OnClose = () => { Console.WriteLine("Connection Closed!"); offer = null; allSockets.Remove(socket); }; socket.OnMessage = message => { Console.WriteLine(message); HandleMessage(message); }; }); }
/// <summary> /// 消息到达 /// </summary> /// <param name="sender"></param> /// <param name="connId"></param> /// <param name="final"></param> /// <param name="opCode"></param> /// <param name="mask"></param> /// <param name="data"></param> /// <returns></returns> public HandleResult OnMessage(IWebSocketServer sender, IntPtr connId, bool final, OpCode opCode, byte[] mask, byte[] data) { Console.WriteLine($"OnMessage({connId}), final: {final}, op code: {opCode}, data length: {data.Length}"); var ok = sender.Text(connId, $"这里只是一个欢迎页面, 只是欢迎您, 您可以连接到 {(sender.IsSecure ? "wss" : "ws")}://{sender.Uri.Host}:{sender.Uri.Port}/echo"); return(ok ? HandleResult.Ok : HandleResult.Error); }
/// <summary> /// 消息到达 /// </summary> /// <param name="sender"></param> /// <param name="connId"></param> /// <param name="final"></param> /// <param name="opCode"></param> /// <param name="mask"></param> /// <param name="data"></param> /// <returns></returns> public HandleResult OnMessage(IWebSocketServer sender, IntPtr connId, bool final, OpCode opCode, byte[] mask, byte[] data) { Console.WriteLine($"OnMessage({connId}), final: {final}, op code: {opCode}, data length: {data.Length}"); var ok = sender.Send(connId, opCode, data, data.Length); return(ok ? HandleResult.Ok : HandleResult.Error); }
public void StartListener(string host) { if (state == ENetState.Connected) { throw new Exception("Please disconnect at first."); } // 注意:不直接处理的原因是因为后面可能会把Server+Services独立到另外的进程 // 否则通过Session直接可以转发到另外的对象 var ws = new WebSocketServer(host); // 用于仿真端的连接, 仿真 ws.AddService <ScratchLabService>(ScratchLabService.Path, (service) => { service.labDispatcher = new ScratchLabDispatcher(); // 仿真端协议的消息应答通过lab ctrl 进行回应 service.forwardPath = ScratchLabControlService.Path; }); // 用于控制端的连接,控制端发送消息到CtrlService,CtrlService分发到仿真端的控制 ws.AddService <ScratchLabControlService>(ScratchLabControlService.Path, (service) => { service.labDispatcher = new ScratchLabControlDispatcher(this); // 控制端协议的消息应答通过lab 进行回应 service.forwardPath = ScratchLabService.Path; }); ws.StartListening(); mServer = ws; }
public WebSocketServerWrapper(string endPoint) { _webSocketServer = new WebSocketServer(endPoint) { RestartAfterListenError = true }; }
private UseSocket(string Ip) { this._address = Ip; try { _Servier = new WebSocketServer(this._address); _Servier.Start(socket => { socket.OnMessage = msg => { Message(socket.GetPaarmiter(username), msg); }; socket.OnOpen = () => { Open(socket); }; socket.OnClose = () => { OnClose(socket); }; socket.OnBinary = b => { BinaryMessage(socket.GetPaarmiter(username), b); }; }); } catch { throw new Exception("参数错误!来自UseSocket ,初始化失败"); } }
public WebSocketServerWrapper(string serverLoggingAddress) { _webSocketServer = new WebSocketServer(serverLoggingAddress) { RestartAfterListenError = true }; }
public async Task Initialize() { var input = string.Empty; _server = new WebSocketServer($"{Url}:{_port}"); await Task.Run(() => _server.Start(socket => { socket.OnOpen = () => { _msgText.Show($"New client connected: {socket.ConnectionInfo.ClientIpAddress}"); ConnectedSockets.Add(socket); }; socket.OnClose = () => { _msgText.Show($"Client disconnected: {socket.ConnectionInfo.ClientIpAddress}"); ConnectedSockets.Remove(socket); }; socket.OnMessage = message => { _msgText.Show(message); ConnectedSockets.ToList().ForEach(s => s.Send(message)); }; })); }
private void StartServer() { WebSocketServer server = new WebSocketServer(mLocation); mServer = server; server.SupportedSubProtocols = new[] { mBinding.Name }; if (mCertificate != null) { server.Certificate = mCertificate; } if (mGetEnabledSslProtocols != null) { server.EnabledSslProtocols = mGetEnabledSslProtocols(); } mServer.Start(connection => { FleckWampTextConnection <TMessage> wampConnection = new FleckWampTextConnection <TMessage>(connection, mBinding); OnNewConnection(wampConnection); }); }
public virtual void Dispose() { if(InternalSocketServer == null) throw new ObjectDisposedException(GetType().Name); InternalSocketServer.Dispose(); InternalSocketServer = null; }
public HttpWebSocketListener(IHttpServer httpServer, IWebSocketServer webSocketServer) { this.httpServer = httpServer; this.webSocketServer = webSocketServer; listener = new HttpListener(); listener.Prefixes.Add("http://*:8080/"); }
/// <summary> /// 连接打开 /// </summary> /// <param name="sender"></param> /// <param name="connId"></param> /// <returns></returns> public HandleResult OnOpen(IWebSocketServer sender, IntPtr connId) { var httpServer = (IHttpServer)sender.Http; Console.WriteLine($"OnOpen({connId}), cookie: {httpServer.GetHeader(connId, "Cookie")}, user-agent: {httpServer.GetHeader(connId, "User-Agent")}"); return(HandleResult.Ok); }
public CoreServiceHost() { MessageManager = new MessageManager(); CommandManager = new CommandManager(); var webSocketServer = new WebSocketServer(CommandManager); WebSocketSender = webSocketServer; WebSocketServer = webSocketServer; }
public void StopListener() { if (mServer != null) { mServer.StopListening(); mServer.Dispose(); mServer = null; } }
protected SocketServer(IWebSocketServer socketServer) { Ensure.That(socketServer, "socketServer").IsNotNull(); InternalSocketServer = socketServer; Subscriptions = new List<SocketSubscription>(); Routes = new Routes(); OnBootstrap(); }
public JsonApiWebSocketServer(int port, ICoreService coreInstance) { this.coreInstance = coreInstance; this.server = new WebSocketServer($"ws://0.0.0.0:{port}"); this.connections = new List<IWebSocketConnection>(); this.SocketMessage += this.Process; this.SocketOpen += (s, e) => this.connections.Add(e.Connection); this.SocketClose += (s, e) => this.connections.Remove(e.Connection); }
public HttpWebSocketListener(IHttpServer httpServer, IWebSocketServer webSocketServer) { this.httpServer = httpServer; this.webSocketServer = webSocketServer; listener = new HttpListener(); listener.Prefixes.Add("https://*/"); listener.AuthenticationSchemes = AuthenticationSchemes.Basic; }
public CommandProvider(IFileStoreProvider fileStoreProvider) { this.fileStoreProvider = fileStoreProvider; this.portNumber = this.getRandomUnusedPort(); this.phantomWebSocket = new WebSocketServer(string.Format("ws://0.0.0.0:{0}", this.portNumber)); this.OpenPhantomWebSocket(); this.phantomProcess = this.startPhantomJS(this.portNumber); this.waitForPhantomReady(); }
public FlexSoftCommunicationsLayer(IWebSocketServer webSocketServer, ConcurrentDictionary <IWebSocketConnection, ISocketClient> joinedClients, ConcurrentBag <SocketRoom> socketRooms, ILifetimeScope lifetimeScope) { _webSocketServer = webSocketServer; _joinedClients = joinedClients; _socketRooms = socketRooms; _lifetimeScope = lifetimeScope; }
public CommandProvider(IFileStoreProvider fileStoreProvider) { this.fileStoreProvider = fileStoreProvider; this.portNumber = this.getRandomUnusedPort(); this.phantomWebSocket = new WebSocketServer(string.Format("ws://0.0.0.0:{0}", this.portNumber)); this.OpenPhantomWebSocket(); this.phantomProcess = this.startPhantomJS(this.portNumber); this.waitForPhantomReady(); }
private void StopServerIfNeeded() { lock (mLock) { if (!mSubject.HasObservers) { mServer.Dispose(); mServer = null; } } }
/// <summary> /// 握手成功, 打开/进入 连接 /// </summary> /// <param name="sender"></param> /// <param name="connId"></param> /// <returns></returns> public virtual HandleResult OnOpen(IWebSocketServer sender, IntPtr connId) { #if NET20 || NET30 || NET35 lock (_connectionIds) { _connectionIds.Add(connId); } #else _connectionIds.Add(connId); #endif return(HandleResult.Ok); }
/// <summary> /// 连接关闭 /// </summary> /// <param name="sender"></param> /// <param name="connId"></param> /// <param name="socketOperation"></param> /// <param name="errorCode"></param> /// <returns></returns> public virtual HandleResult OnClose(IWebSocketServer sender, IntPtr connId, SocketOperation socketOperation, int errorCode) { #if NET20 || NET30 || NET35 lock (_connectionIds) { _connectionIds.Remove(connId); } #else _connectionIds.TryTake(out var _); #endif return(HandleResult.Ok);; }
public Server() { port = 0; //var input = Console.ReadLine(); //while (input != "exit") //{ // foreach (var socket in allSockets.ToList()) // { // socket.Send(input); // } // input = Console.ReadLine(); //} server = new WebSocketServer("ws://0.0.0.0:" + port.ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="ChatServer" /> class. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="port">The port.</param> /// <param name="serverAddress">The server address.</param> public ChatServer(string userName, string serverAddress) : base(userName, true) { if (serverAddress == null) { throw new ArgumentNullException(nameof(serverAddress)); } this.webSocketServer = new WebSocketServer(serverAddress) { RestartAfterListenError = true }; this.clients = new ConcurrentDictionary <Guid, IWebSocketConnection>(); }
public Server() { port = 0; //var input = Console.ReadLine(); //while (input != "exit") //{ // foreach (var socket in allSockets.ToList()) // { // socket.Send(input); // } // input = Console.ReadLine(); //} server = new WebSocketServer("ws://0.0.0.0:" + port.ToString()); }
public ServiceHost() { var config = new LocalConfigHelper(Assembly.GetExecutingAssembly().Location, " WebSocket Service"); IP = config.GetString(nameof(IP)); Port = config.GetInt(nameof(Port)); var core = new CoreServiceHost(); _commandManager = core.CommandManager; _webSocketServer = core.WebSocketServer; _core = core; RegsterCommands(); }
/// <summary> /// 连接打开 /// </summary> /// <param name="sender"></param> /// <param name="connId"></param> /// <returns></returns> public HandleResult OnOpen(IWebSocketServer sender, IntPtr connId) { var httpServer = (IHttpServer)sender.Http; Console.WriteLine($"OnOpen({connId}), cookie: [{httpServer.GetHeader(connId, "Cookie")}], user-agent: [{httpServer.GetHeader(connId, "User-Agent")}]"); var str = "Websocket是一种用于H5浏览器的实时通讯协议,可以做到数据的实时推送,可适用于广泛的工作环境,例如客服系统、物联网数据传输系统。"; // 发送文本消息1 var bytes = Encoding.UTF8.GetBytes(str); var ok = sender.Send(connId, OpCode.Text, bytes, bytes.Length); // 发送文本消息2 // var ok = sender.Text(connId, str); return(ok ? HandleResult.Ok : HandleResult.Error); }
/// <summary> /// Main Invoke Method /// </summary> /// <param name="context">Http Context</param> /// <param name="webSocketServer">WebSocket Server</param> /// <returns><see cref="Task"/></returns> public async Task Invoke(HttpContext context, IWebSocketServer webSocketServer) { // Bypass None WebSocket Requests if (!context.WebSockets.IsWebSocketRequest) { await this._next.Invoke(context); return; } this._webSocketServer = webSocketServer; // Grab the Cancellation Token for [RequestAborted] // todo: Fix this so that the CancellationToken is derived from the ApplicationLifetime instead! var cancellationToken = context.RequestAborted; // Accept the Incoming WebSocket var socket = await context.WebSockets.AcceptWebSocketAsync(); // Get the Client Name var clientName = context.Request.Headers.FirstOrDefault(p => p.Key == CLIENT_NAME).Value; // Add the Socket to the Connection Manager var socketId = await this._webSocketServer.AddSocketAsync(socket, clientName); // Process incoming messages while (socket.State == WebSocketState.Open) { try { await this.ReceiveAsync(socket, cancellationToken); } catch (Exception e) { Console.WriteLine(e); throw; } } // Close the Connection await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, CLOSURE_MESSAGE, cancellationToken); // Remove the Connection from the Connection Manager await this._webSocketServer.RemoveSocketAsync(socketId); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider, IApplicationLifetime applicationLifetime) { SocketHandler.Map(app); serviceProvider.GetService <CapHandler>().MessageHandler(); app.UseWebApi(_env); app.UseStateAutoMapper(); IWebSocketServer socket = null; applicationLifetime.ApplicationStarted.Register(() => { socket = app.ApplicationServices.GetRequiredService <ISocketService>() .StartAsync().ConfigureAwait(false).GetAwaiter().GetResult(); }); applicationLifetime.ApplicationStopping.Register(() => { socket?.Close(); }); }
public void Start(IWebSocketServer webSocketServer, Action onOpen, Action onClose) { var allSockets = new List <IWebSocketConnection>(); webSocketServer.Start(socket => { socket.OnOpen = () => { onOpen.Invoke(); allSockets.Add(socket); }; socket.OnClose = () => { onClose.Invoke(); _ = allSockets.Remove(socket); }; socket.OnMessage = message => allSockets.ToList().ForEach(s => s.Send(message)); }); }
public RemoteSessionSocketServer(Global global, IWebSocketServer server) { // websockets are not bound to an http context... the remote session manager must be retrieved from an application perspective _global = global; // logs FleckLog.Level = LogLevel.Warn; FleckLog.LogAction = (level, message, ex) => { switch (level) { case LogLevel.Debug: Trace.TraceInformation(message, ex); break; case LogLevel.Warn: Trace.TraceWarning(message, ex); break; case LogLevel.Error: Trace.TraceError(message, ex); break; default: Trace.TraceInformation(message, ex); break; } }; // sockets _sockets = new List <IWebSocketConnection>(); _socketsLock = new object(); // start sockets server server.Start(socket => { socket.OnOpen = () => { Open(socket); }; socket.OnMessage = message => ProcessMessage(socket, message); socket.OnError = exception => { Trace.TraceError("Websocket error {0}", exception); }; socket.OnClose = () => { Close(socket); }; }); }
/// <summary> /// 启动服务 /// </summary> /// <returns></returns> public async Task <IWebSocketServer> StartAsync() { var port = _configuration.GetValue <int>("WebSocketPort"); _socket = await SocketBuilderFactory.GetWebSocketServerBuilder(port) .OnConnectionClose((server, connection) => { _logger.LogInformation($"连接关闭,连接名[{connection.ConnectionName}],当前连接数:{server.GetConnectionCount()}"); RemoveConnection(connection.ConnectionId); }) .OnException(ex => { _logger.LogError(ex, $"服务端异常:{ex.Message}"); }) .OnNewConnection((server, connection) => { connection.ConnectionName = $"{connection.ClientAddress.ToString()}"; _logger.LogInformation($"新的连接:{connection.ConnectionName},当前连接数:{server.GetConnectionCount()}"); }) .OnRecieve((server, connection, msg) => { if (msg.HasVal() && msg.StartsWith("InformIdentity_")) { var userId = msg.Replace("InformIdentity_", string.Empty); if (userId.HasVal()) { AddConnection(userId, connection.ConnectionId); connection.Send("InformIdentity_ok"); } } }) .OnSend((server, connection, msg) => { _logger.LogInformation($"向连接名[{connection.ConnectionName}]发送数据:{msg}"); }) .OnServerStarted(server => { _logger.LogInformation($"服务启动"); }).BuildAsync(); return(_socket); }
private UseSocket(string Ip) { this._address = Ip; _Servier = new WebSocketServer(this._address); _Servier.Start(socket => { socket.OnMessage = msg => { Message(socket.GetPaarmiter(username), msg); }; socket.OnOpen = () => { Open(socket); }; socket.OnClose = () => { OnClose(socket); }; socket.OnBinary = b => { BinaryMessage(socket.GetPaarmiter(username), b); }; }); }
/// <summary> /// pong 消息 /// </summary> /// <param name="sender"></param> /// <param name="connId"></param> /// <param name="data"></param> public virtual void OnPong(IWebSocketServer sender, IntPtr connId, byte[] data) { }
//Initializes the web socket server that listens for incoming requests private static void InitializeWebSockets() { allSockets = new List<IWebSocketConnection>(); server = new WebSocketServer(WEB_SOCKET_SERVICE_URL); server.Start(socket => { socket.OnOpen = () => { Console.WriteLine("Connection Opened"); offer = null; allSockets.Add(socket); }; socket.OnClose = () => { Console.WriteLine("Connection Closed!"); offer = null; allSockets.Remove(socket); }; socket.OnMessage = message => { Console.WriteLine(message); HandleMessage(message); }; }); }
void IBaseHttpServer.StopServer() { this.server.Dispose(); this.serverThread.Abort(); this.server = null; this.serverThread = null; }
/// <summary> /// cont/text/binary 消息 /// </summary> /// <param name="sender"></param> /// <param name="connId"></param> /// <param name="final"></param> /// <param name="opCode"></param> /// <param name="mask"></param> /// <param name="data"></param> /// <returns></returns> public virtual HandleResult OnMessage(IWebSocketServer sender, IntPtr connId, bool final, OpCode opCode, byte[] mask, byte[] data) => HandleResult.Ok;
public NodeService(IWebSocketServer clientWebSocket) { this.openClientConnections = new Dictionary<IWebSocketConnection, TestProcessor>(); this.clientWebSocket = clientWebSocket; }
public WebSocketManager(string Host, uint Port) { string location = "ws://" + Host + ":" + Port; _webSocketServer = new WebSocketServer(location); FleckLog.Level = LogLevel.Error; _webSocketClientManager = new WebSocketClientManager(); _webSocketHandlerManager = new WebSocketHandlerManager(); _webSocketServer.Start(socket => { socket.OnOpen = () => { var Uuid = Guid.NewGuid().ToString(); log.Info("Connection created -> " + socket.ConnectionInfo.ClientIpAddress + " (" + Uuid + ")"); var socketClient = new WebSocketClient(Uuid, socket); _webSocketClientManager.RegisterSocketClient(socketClient); socketClient.Send(new HeyHandler(Uuid)); }; socket.OnClose = () => { var socketClient = _webSocketClientManager.GetWebSocketClient(socket); GameEnvironment.GetGameManager().DestroyGame(socketClient.Game); log.Info("Connection destroyed -> " + socket.ConnectionInfo.ClientIpAddress + " (" + socketClient.Uuid + ")"); _webSocketClientManager.DeregisterSocketClient(socket); }; socket.OnMessage = (message) => { try { var Payload = JsonConvert.DeserializeObject <MessageObject>(message); if (Payload.Event == null) { throw new Exception("No event handler was passed."); } var Handler = _webSocketHandlerManager.GetIncomingEventHandler(Payload.Event); if (Handler == null) { throw new Exception("No handler was found for specified identifier"); } var SocketClient = _webSocketClientManager.GetWebSocketClient(socket); if (SocketClient == null) { throw new Exception("No SocketClient instance was found for the socket connection"); } LogMessage(SocketClient.Uuid, message); Handler.Execute(SocketClient, Payload); } catch (Exception ex) { log.Error(ex); } }; }); log.Info("WebSocketManager (" + location + ") -> LOADED!"); }