public bool KeepAlive() { int oldConnections; int newConnections; lock (WebSockets) { oldConnections = WebSockets.Count; // Clean up all client connections. for (int i = WebSockets.Count - 1; i >= 0; --i) { // Remove a connection if its state is closed, closing or aborted. if (WebSockets[i].State == WebSocketState.Aborted || WebSockets[i].State == WebSocketState.Closed || WebSockets[i].State == WebSocketState.CloseReceived) { WebSockets.RemoveAt(i); } } newConnections = WebSockets.Count; } // Emit client connection changed event if connection count has changed. if (oldConnections != newConnections) { OnClientConnectionChanged(newConnections); } // Tell if the server is still listening. return(Listener.IsListening); }
/// <summary> /// Called when this WebSockets Server receives a full message (EndOfMessage) form a WebSockets client. /// </summary> /// <param name="context">The context.</param> /// <param name="rxBuffer">The rx buffer.</param> /// <param name="rxResult">The rx result.</param> protected override void OnMessageReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult) { foreach (var ws in WebSockets.Where(ws => ws != context)) { Send(ws, Encoding.UTF8.GetString(rxBuffer)); } }
/// <inheritdoc /> protected override void OnMessageReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { foreach (var ws in WebSockets.Where(ws => ws != context)) { Send(ws, rxBuffer.ToText()); } }
/// <summary> /// Broadcasts the specified payload to all connected WebSockets clients. /// </summary> /// <param name="payload">The payload.</param> protected virtual void Broadcast(string payload) { var sockets = WebSockets.ToArray(); foreach (var wsc in sockets) { Send(wsc, payload); } }
public async Task Remove(WebSocketKey id) { WebSocket socket; WebSockets.TryRemove(id, out socket); await socket.CloseAsync(closeStatus : WebSocketCloseStatus.NormalClosure, statusDescription : "Closed by the WebSocketCollection", cancellationToken : CancellationToken.None); }
/// <summary> /// Called when this WebSockets Server accepts a new WebSockets client. /// </summary> /// <param name="context">The context.</param> protected override void OnClientConnected(WebSocketContext context) #endif { Send(context, "Welcome to the chat room!"); foreach (var ws in WebSockets.Where(ws => ws != context)) { Send(ws, "Someone joined the chat room."); } }
public void AcessarChat(string chaveAcesso) { if (HttpContext.IsWebSocketRequest || HttpContext.IsWebSocketRequestUpgrading) { var instancia = new WebSockets(chaveAcesso); HttpContext.AcceptWebSocketRequest(instancia); } ; HttpContext.Response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; }
/// <inheritdoc /> protected override void OnClientConnected( IWebSocketContext context, System.Net.IPEndPoint localEndPoint, System.Net.IPEndPoint remoteEndPoint) { Send(context, "Welcome to the chat room!"); foreach (var ws in WebSockets.Where(ws => ws != context)) { Send(ws, "Someone joined the chat room."); } }
private static Boolean ResponseToStation(ScriptBuffer ThisBuffer) { Boolean IsSend = false; if (ScriptDBBuffer.Count > 0) { List <ScriptTB> WaitingScriptList = ScriptDBBuffer.Values.Where(Item => Item.ScriptState == "CREATED" || Item.ScriptState == "WAITINGSERVER" && Item.ExecutionNumber == 1).ToList(); if (WaitingScriptList.Count > 0) { while (WaitingScriptList.Count > 0) { String Message = ""; Boolean IsAllScriptRecived = IsBlockComplete(WaitingScriptList[0], out Message); if (IsAllScriptRecived) { if (!VerifyTotalExecutionTime(WaitingScriptList[0])) { if (ThisBuffer != null) { WebSockets.ReturnScriptResult(ThisBuffer.WSConnection, ThisBuffer.Script.BlockName, ThisBuffer.Script.BlockID, ThisBuffer.Script.ExecutionNumber.ToString(), ThisBuffer.Script.CommandName.ToString(), "All script is sending to client.", "Script_Success"); } List <ScriptTB> InValidScript = ScriptDBBuffer.Values.Where(Item => Item.BlockID == WaitingScriptList[0].BlockID).ToList(); foreach (ScriptTB ThisScript in InValidScript) { ScriptTB TempScript = null; ScriptDBBuffer.TryRemove(ThisScript.BlockID + ThisScript.ExecutionNumber, out TempScript); DatabaseSynchronization.DeleteScript(TempScript); RemoveScriptToMonitoring(TempScript); } return(false); } SendScriptToStation(WaitingScriptList[0]); WaitingScriptList.RemoveAll(Item => Item.BlockID == WaitingScriptList[0].BlockID); IsSend = true; } else { WaitingScriptList.RemoveAt(0); } } } } return(IsSend); }
public void AddWebSocket(PodeWebSocket webSocket) { lock (WebSockets) { if (WebSockets.ContainsKey(webSocket.ClientId)) { WebSockets[webSocket.ClientId] = webSocket; } else { WebSockets.Add(webSocket.ClientId, webSocket); } } }
private void ClientGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex >= 0 && e.ColumnIndex >= 0) { String IPAddress = ClientGrid[1, e.RowIndex].Value.ToString(); String Port = ClientGrid[2, e.RowIndex].Value.ToString(); List <String> ThisMessage = WebSockets.GetMonitoringInformation(IPAddress, Port); if (ThisMessage != null) { ObjPackageMonitoring.SetInformation(ThisMessage); ObjPackageMonitoring.ClientInformationSetter(IPAddress, Port); ObjPackageMonitoring.Show(); } } }
private static void ResponseToClient(ScriptBuffer ThisBuffer) { if (ThisBuffer != null) { String Message = ""; Boolean IsAllScriptRecived = IsBlockComplete(ThisBuffer.Script, out Message); if (IsAllScriptRecived) { WebSockets.ReturnScriptResult(ThisBuffer.WSConnection, ThisBuffer.Script.BlockName, ThisBuffer.Script.BlockID, ThisBuffer.Script.ExecutionNumber.ToString(), ThisBuffer.Script.CommandName.ToString(), "All script is sending to client.", "Script_Success"); } else { WebSockets.ReturnScriptResult(ThisBuffer.WSConnection, ThisBuffer.Script.BlockName, ThisBuffer.Script.BlockID, ThisBuffer.Script.ExecutionNumber.ToString(), ThisBuffer.Script.CommandName.ToString(), Message, "Script_OK"); } } }
/// <summary> /// Tickerを受信するWebSocketを追加する /// 受信時のイベントを登録する /// 後の処理はCandleMakerに任せる /// </summary> /// <param name="myWebSocket">Tickerを受信するWebSocket</param> /// <param name="board">MBoard</param> /// <param name="timeScales">時間足リスト、時間が短い順</param> public void AddWebSocket(MyWebSocket myWebSocket, MBoard board, List <MTimeScale> timeScales) { // ローソク作成クラスを作成する var candleMaker = CandleMaker.MakeGeneration(Logger, DbContext, timeScales, board); // 受信時のイベント設定 if (board.Name.StartsWith(SystemConstants.BoardPrefixBitflyer)) { // BFの場合 myWebSocket.GetMessage += (obj, e) => { var textEvent = e as TextEventArgs; var ticker = JsonConvert.DeserializeObject <LightningTicker>(textEvent.Text); // tickerをこのWSに対応したローソク作成クラスの一番親に送る candleMaker.Update(new Ticker(ticker)); }; } // リストに追加 CandleMakers.Add(board.Name, candleMaker); WebSockets.Add(board.Name, myWebSocket); }
public void AddDeviceData(STATIONNAME StationName, String ScriptsJSON, Boolean IsInsertDB = true, Boolean IsSentWebSocket = true) { //Console.WriteLine(StationName); Task DeviceTask = Task.Run(() => { if (ScriptsJSON == null) { return; } if (ScriptsJSON[0] != '[' && ScriptsJSON['1'] != '{') { ScriptsJSON = StringCompression.DecompressString(ScriptsJSON); } if (ScriptsJSON == null) { return; } //Console.WriteLine("AddDeviceData - " + StationName.ToString() + " (" + Datas[0].DataId + ") - Packet: " + Datas.Count() + " Rows"); DataPacket[] Datas = (DataPacket[])Newtonsoft.Json.JsonConvert.DeserializeObject(ScriptsJSON, typeof(DataPacket[])); StationHandler StationCommunication = AstroData.GetStationObject(StationName); foreach (DataPacket Data in Datas) { //if (Data.FieldName == "IMAGING_FILTER_FILTERPOSITION") //{ // Console.WriteLine(Data.Value); //} if (Data.DeviceCategory == DEVICECATEGORY.CCTV) { //Console.WriteLine(Data.Value); if (Data.FieldName.ToString() == CCTV.CCTV_DEVICE1_IMAGE.ToString() || Data.FieldName.ToString() == CCTV.CCTV_DEVICE2_IMAGE.ToString()) { Data.Value = Convert.ToBase64String(((JArray)Data.Value).ToObject <byte[]>()); } } else if (Data.DeviceCategory == DEVICECATEGORY.ALLSKY) { if (Data.FieldName.ToString() == ALLSKY.ALLSKY_IMAGE.ToString()) { //Console.WriteLine("RECEIVED ALLSKY: " + IsSentWebSocket); if (typeof(JArray).Equals(Data.Value.GetType())) { Data.Value = Convert.ToBase64String(((JArray)Data.Value).ToObject <byte[]>()); } } } else if (Data.DeviceCategory == DEVICECATEGORY.IMAGING) { //Console.WriteLine(Data.FieldName); if (Data.FieldName.ToString() == IMAGING.IMAGING_CCD_DOWNLOAD_STATUS.ToString()) { String[] TempValue = Data.Value.ToString().Split(';'); if (TempValue.Count() > 1) { if (TempValue[0] == "Completed") { // BlockID#/files/AIRFORCE/FITS/maIeayp9iEO57G9LXZVPA_TakenFromClient.FITS String[] PreFileName = TempValue[1].Split('#'); if (PreFileName.Count() > 1) { String BlockID = PreFileName[0]; String[] TmpFileName = PreFileName[1].Split('/'); String FileName = TmpFileName[(TmpFileName.Count() - 1)] + ".FITS"; String[] TempTargetID = FileName.Split('_'); String TargetID = TempTargetID[0]; DBScheduleEngine.InsertFITSData(TargetID, BlockID, StationName, FileName, Data.DateTimeUTC, DateTime.UtcNow.Ticks); } Data.Value = "Completed"; } } } else if (Data.FieldName.ToString() == IMAGING.IMAGING_PREVIEW_DOWNLOAD_STATUS.ToString()) { AstroData.LoadPerviewImage(StationName, Data.DeviceName, StationCommunication); } //AstroData.NewIMAGINGInformationHandle(StationName, Data.DeviceName, Data.FieldName, Data.Value, new DateTime(Data.DateTimeUTC)); } if (IsInsertDB) { DBScheduleEngine.InsertData(Data.DataId, StationName, Data.DeviceCategory, Data.DeviceName, Data.FieldName, Data.Value, Data.DateTimeUTC); } if (IsSentWebSocket) { WebSockets.ReturnWebSubscribe(StationName, Data.DeviceName, Data.FieldName.ToString(), Data.Value, new DateTime(Data.DateTimeUTC)); } AstroData.UpdateInformation(StationName, Data.DeviceName, Data.FieldName, Data.Value, new DateTime(Data.DateTimeUTC)); } }); }
private void InitializeWS() { ObjPackageMonitoring = new PackageMonitoring(); WebSockets.CreateConnection(ClientGrid, this, TTCSLogGrid, Properties.Settings.Default.SocketServerAddress); }
/// <summary> /// Broadcasts the specified payload to all connected WebSockets clients. /// </summary> /// <param name="payload">The payload.</param> protected virtual void Broadcast(string payload) { WebSockets.ToList() .ForEach(wsc => Send(wsc, payload)); }
/// <summary> /// Add web socket middleware to owin pipeline that is built using IAppBuilder. /// </summary> /// <param name="appBuilder">The application builder.</param> /// <param name="path">The path to handle websocket requests.</param> /// <param name="onAccept">A delagete that is invoked when a websocket request has been received.</param> /// <returns>The application builder.</returns> public static IAppBuilder UseWebSockets(this IAppBuilder appBuilder, string path, Func <IWebSocketContext, Task> onAccept) { appBuilder.Use(WebSockets.UseWebsockets(path, onAccept)); return(appBuilder); }
public List <WebSocket> GetAll(string channel) { return(WebSockets.Where(x => x.Key.Channel == channel).Select(x => x.Value).ToList()); }
internal void SetExtensions(WebSockets.IExtension[] extensions) { this.Extensions = extensions; }
public async Task AddWebSocketHandler(WebSocketHandler socket) { WebSockets.TryAdd(socket.GetId(), socket.GetWebSocket()); }
public CustomWebSocket Get(string userId) { return(WebSockets.FirstOrDefault(w => w.UserId == userId)); }