private async void BeginPoll() { var longpoll = await _api.Groups.GetLongPollServerAsync(GroupId); var parameters = new LongpollParameters(longpoll); const int timeout = 25; using (var client = new HttpClient()) { client.Timeout = TimeSpan.FromSeconds(timeout); while (true) { var request = new HttpRequestMessage(HttpMethod.Get, parameters.GetUrl(timeout)); using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) using (var body = await response.Content.ReadAsStreamAsync()) using (var reader = new StreamReader(body)) { var json = reader.ReadToEnd(); var result = JsonConvert.DeserializeObject <LongpollResponse>(json); foreach (var message in result.Updates) { MessageRecieved?.Invoke(message.ToRecivedMessage()); } await parameters.Update(_api, result); } } } // ReSharper disable once FunctionNeverReturns }
private void Consumer_Received(object sender, BasicDeliverEventArgs e) { var message = e.Body.Deserialize(); Logger.Info($"recieved {message}"); MessageRecieved?.Invoke(this, message); }
public void ReadCallback(IAsyncResult ar) { string content = string.Empty; StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead)); content = state.sb.ToString(); if (content.IndexOf("<!Nickname>") > -1) { Client client = new Client(connectionsCounter, handler, content.Replace("<!Nickname>", "")); ClientAccepted.Invoke(this, new ClientAcceptedEventArgs(client)); connectionsCounter++; } else if (content.IndexOf("<!Message>") > -1) { MessageRecieved.Invoke(this, new MessageRecievedEventArgs(new Message(messagesCounter, MessageType.TextMessage, Encoding.UTF8.GetBytes(content)))); messagesCounter++; } else { return; } } }
/// <summary> /// Задача чтения из потока /// </summary> /// <returns></returns> public async Task Read() { byte[] data = new byte[64]; while (!cancellationToken.IsCancellationRequested) { StringBuilder builder = new StringBuilder(); do { var bytes = await stream.ReadAsync(data, 0, data.Length, cancellationToken.Token); builder.Append(Encoding.UTF8.GetString(data, 0, bytes)); }while (stream.DataAvailable && !cancellationToken.Token.IsCancellationRequested); var message = builder.ToString(); if (string.IsNullOrWhiteSpace(message)) { Disconnected?.Invoke(Guid); _ = Disconnect(); Dispose(); } else { message.Split(separator, StringSplitOptions.RemoveEmptyEntries) .AsParallel() .ForAll(mes => MessageRecieved?.Invoke(Guid, mes)); } } }
/// <summary> /// 接收器工作 /// </summary> /// <returns></returns> public async Task ReceiveAsync() { using (var client = new UdpClient(Port)) { if (GroupAddress != null) { Logger.Debug($"Join Multicast Group = {GroupAddress}"); client.JoinMulticastGroup(IPAddress.Parse(GroupAddress)); } Logger.Debug("Start Listening...Sending in [stop] to stop listening"); bool completed; do { UdpReceiveResult result = await client.ReceiveAsync(); byte[] datagram = result.Buffer; MessageRecieved?.Invoke(this, new UdpReceivedEventArgs(datagram)); string received = Encoding.UTF8.GetString(datagram); Logger.Info($"Received (from {result.RemoteEndPoint.Address}) < {received}"); completed = (received.ToLower() == "stop"); } while (!completed); if (GroupAddress != null) { client.DropMulticastGroup(IPAddress.Parse(GroupAddress)); } Logger.Warn("Listening stop command received."); Logger.Warn("Udp is stopping..."); } }
public void Log(string message, MessageTypeEnum type) { MessageRecieved?.Invoke(this, new MessageRecievedEventArgs() { Message = message, Status = type }); // Notifying about the Message }
private async void WriteData(CancellationToken cancelationToken, Channel <IFrame> sourceQueue) { try { IFrame frame; int Nprocesssed = 0; while (await sourceQueue.Reader.WaitToReadAsync(cancelationToken)) { if (!sourceQueue.Reader.TryRead(out frame)) { continue; } Nprocesssed++; foreach (KeyValuePair <string, ITimeSeriesValue> value in frame.Measurements) { SignalWritter writer; if (m_writers.TryGetValue(value.Key, out writer)) { writer.AddPoint(value.Value); } } } } catch (Exception ex) { MessageRecieved?.Invoke(this, new MessageArgs("An error occurred writing data to the temporary files", MessageArgs.MessageLevel.Error)); } finally { m_writers.Values.ToList().ForEach(item => item.Complete()); } }
/// <summary> /// Adding the log registers the given message. /// </summary> /// <param name="message"> The message text </param> /// <param name="type"> The message type - information, warning etc. </param> public void Log(string message, MessageTypeEnum type) { string msg = type.ToString() + "|" + message; fullLog.Add(msg); MessageRecieved?.Invoke(this, new MessageRecievedEventArgs(type, message)); }
private void onMessage(object sender, WebSocketSharp.MessageEventArgs evt) { if (MessageRecieved != null) { MessageRecieved.Invoke(evt.Data); } }
private async void GetData(CancellationToken cancelationToken) { try { m_Source.MessageRecieved += ProcessMessage; int count = 0; if (!m_Source.SupportProgress) { ProgressArgs args = new ProgressArgs("This DataSource does not support Progress updates.", false, (int)50); ReportProgress?.Invoke(this, args); } await foreach (IFrame frame in m_Source.GetData(m_sourceSignals, m_start, m_end)) { frame.Timestamp = Ticks.AlignToMicrosecondDistribution(frame.Timestamp, m_commonFrameRate); await m_sourceQueue.Writer.WriteAsync(frame, cancelationToken); count++; if (count % 1000 == 0 && m_Source.SupportProgress) { ReportDatasourceProgress(m_Source.GetProgress()); } } } finally { MessageRecieved?.Invoke(this, new MessageArgs("Finished Loading Data from DataSource", MessageArgs.MessageLevel.Info)); m_sourceQueue.Writer.Complete(); } }
public TestConnectionManager() { _timeServerTimer = new Timer { Interval = 5000 }; _timeServerTimer.Elapsed += (sender, args) => { MessageRecieved?.Invoke(this, new Message() { Sender = _timeServer, Content = "Current time: " + DateTime.Now.ToShortTimeString(), TimeStamp = DateTime.Now }); }; _joeTimer = new Timer(10000); _joeTimer.Elapsed += (sender, args) => { var message = new Message { Sender = Constants.ServerId, TimeStamp = DateTime.Now }; if (_isJoeHere) { message.Content = $"user {_joe} left"; MessageRecieved?.Invoke(this, message); } else { message.Content = $"user {_joe} joined"; MessageRecieved?.Invoke(this, message); } _isJoeHere = !_isJoeHere; }; }
private void WaitForConnectionCallBack(IAsyncResult asyncResult) { try { NamedPipeServerStream pipeServer = (NamedPipeServerStream)asyncResult.AsyncState; pipeServer.EndWaitForConnection(asyncResult); byte[] messageBuffer = new byte[1024]; pipeServer.Read(messageBuffer, 0, 1024); string message = Encoding.UTF8.GetString(messageBuffer, 0, messageBuffer.Length); Debug.WriteLine(message + Environment.NewLine); MessageRecieved.Invoke(message); pipeServer.Close(); pipeServer = null; pipeServer = new NamedPipeServerStream(m_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); if (ShutdownRequested) { return; } // Recursively wait for the connection again pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer); } catch { return; } }
/// <summary> /// Reads all messages from the other client and raises the appropriate event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void GameReader_DoWork(object sender, DoWorkEventArgs e) { var reader = (StreamReader)e.Argument; string currentString; Message <object> currentMessage; while (tcpClient.Connected) { try { currentString = reader.ReadLine(); } catch (Exception) { currentString = null; } if (!(currentString == null || currentString == "")) { currentMessage = JsonConvert.Deserialise <Message <object> >(currentString); if (currentMessage != default(Message <object>)) { if (currentMessage.Type == typeof(string).ToString()) { MessageRecieved?.Invoke(null, new GameConnectionEventArgs <string>(JsonConvert.Deserialise <Message <string> >(currentString).Data, currentString)); } else if (currentMessage.Type == typeof(Point).ToString()) { LocationRecieved?.Invoke(null, new GameConnectionEventArgs <Point>(JsonConvert.Deserialise <Message <Point> >(currentString).Data, currentString)); } } } } StopGame(); }
/// <summary> /// Triggered when raw message received. /// </summary> /// <param name="sender">IMessageClient</param> /// <param name="e">Raw message</param> private async void OnRawMessageReceived(object sender, string e) { // About once every five minutes, the server sends a PING. // To ensure that your connection to the server is not prematurely terminated, reply with PONG if (e.StartsWith("PING")) { controller._log.LogMessage($"Twitch Client Ping"); Task pong = SendPongResponseAsync(); await pong; if (pong.Status != TaskStatus.RanToCompletion) { controller._log.LogError($"Sending Pong Failed! {pong.Status}"); } if (pong.Status == TaskStatus.RanToCompletion) { controller._log.LogMessage($"Twitch Client replied with Pong."); } return; } try { MessageRecieved?.Invoke(sender, e); } catch { }; if (TryParsePrivateMessage(e, out Message message)) { _channel?.ReceiveMessage(message); } }
private void Start() { while (true) { var longPollServerResponse = _vkApi.Groups.GetLongPollServer(ConfigManager.Config.VK.GroupId); var poll = _vkApi.Groups.GetBotsLongPollHistory( new BotsLongPollHistoryParams() { Server = longPollServerResponse.Server, Ts = longPollServerResponse.Ts, Key = longPollServerResponse.Key, Wait = 25 }); if (poll?.Updates == null) { continue; } foreach (var update in poll.Updates) { if (update.Type == GroupUpdateType.MessageNew) { Console.WriteLine(update.MessageNew.Message.Text); MessageRecieved?.Invoke(update.MessageNew.Message.Text, update.MessageNew.Message.PeerId); } } } }
public async void ReadMessage() { var client = new ClientWebSocket(); var cts = new CancellationTokenSource(); await client.ConnectAsync(new Uri(_conversation.StreamUrl), cts.Token); await Task.Factory.StartNew(async() => { while (true) { WebSocketReceiveResult result; var message = new ArraySegment <byte>(new byte[4096]); do { result = await client.ReceiveAsync(message, cts.Token); if (result.MessageType != WebSocketMessageType.Text) { break; } var messageBytes = message.Skip(message.Offset).Take(result.Count).ToArray(); string messageJson = Encoding.UTF8.GetString(messageBytes); BotResponse botResponse = JsonConvert.DeserializeObject <BotResponse>(messageJson); var args = new BotResponseEventAgrs(); args.Activities = botResponse.Activities; MessageRecieved?.Invoke(this, args); }while (!result.EndOfMessage); } }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
private void ParseMessages() { var data = _stringBuilder.ToString(); string[] messages = data.Split(new string[] { NetworkConstants.MESSAGE_TERMINATOR }, StringSplitOptions.RemoveEmptyEntries); _stringBuilder.Clear(); string singleMessage = String.Empty; for (int i = 0; i < messages.Length - 1; i++) { singleMessage = messages[i]; try { NetworkMessage networkMessage = NetworkMessage.Deserialize(singleMessage); Console.WriteLine("RECEIVE: " + networkMessage.Message); MessageRecieved?.Invoke(this, new NetworkMessageReceivedEventArgs(_clientid, networkMessage)); } catch (NetworkSerializationException e) { _stringBuilder.Append(singleMessage); _stringBuilder.Append(NetworkConstants.MESSAGE_TERMINATOR); } } }
private void RequestProcessor(HttpListenerContext context) { byte[] response; { // The input from the user HttpListenerRequest request = context.Request; using (Stream s = request.InputStream) { byte[] returnBytes = new byte[request.ContentLength64]; s.Read(returnBytes, 0, returnBytes.Length); response = MessageRecieved?.Invoke(returnBytes, request); } } if (response != null) { context.Response.ContentLength64 = response.Length; using (Stream stream = context.Response.OutputStream) { stream.Write(response, 0, response.Length); } } }
protected bool RaiseMessageRecieved(TorchChatMessage msg) { var consumed = false; MessageRecieved?.Invoke(msg, ref consumed); return(consumed); }
/// <summary> /// Handles incoming websocket events, acts accordingly. /// </summary> /// <param name="sender"></param> /// <param name="response"></param> private void WebSocketDataRecieved(object sender, RoomSocket response) { switch (response.message) { // The user has been added to the room case "allocation": webSocketService.token = response.token; webSocketService.roomId = response.room; GetRoomMedia(); break; // There is a change in the state of the media case "mediaChange": Room.CurrentMedia = response.media; MediaChanged?.Invoke(this, new EventArgs()); break; // A message from a user, that was broadcasted to the room is recieved case "message": Room.AddMessage(response.messageData); MessageRecieved?.Invoke(this, new EventArgs()); break; default: break; } }
/* * The function loggs recieved massage */ public void Log(string message, MessageTypeEnum type) { LogObject newLog = new LogObject(type.ToString(), message); Logs.Add(newLog); MessageRecieved?.Invoke(this, new MessageRecievedEventArgs(type, message)); }
protected void onMessageReceived(ClientConnection connection, Message msg) { this.control.Invoke((MethodInvoker)(() => { MessageRecieved?.Invoke(this, msg); })); }
/// <summary> /// Recieve messages from the client. /// </summary> public void recieveMessage() { while (true) { // Reading the message from the stream. char[] messageBuffer = new char[10000]; reader.Read(messageBuffer, 0, 10000); string message = new string(messageBuffer); if (isClosed(message)) { // Getting the whole message without (#) message = Regex.Match(message, "#(.+)#").Groups[1].Value + "\r\n"; MessageRecieved?.Invoke(message); connectionEnded?.Invoke(this.Name); return; } if (messageBuffer[0] != '\0') { message += "\r\n"; // Firing the event. MessageRecieved?.Invoke(message); } else { return; } } }
/*the function recieves a message and invoke the logger recieving mechanism (to write down the message). * param name = message is a message to logger * param name = type is a type of message */ public void Log(string message, MessageTypeEnum type) { MessageReceivedEventArgs msg = new MessageReceivedEventArgs(type, message); MessageRecieved?.Invoke(this, msg); allLogs.Add(msg); //add msg to list of logs. }
protected async virtual void OnMessageRecieved(BTMessageRecievedEventArgs e) { await mainPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, delegate { MessageRecieved?.Invoke(this, e); }); }
/// <summary> /// Logs the specified message. /// </summary> /// <param name="message">The message to log.</param> /// <param name="type">The type of the message.</param> public void Log(string message, MessageTypeEnum type) { MessageRecievedEventArgs msgEventArgs = new MessageRecievedEventArgs(); msgEventArgs.Message = message; msgEventArgs.Status = type; MessageRecieved.Invoke(this, msgEventArgs); }
protected virtual void onMessageReceived(MessageReceivedEventArgs args) { // MessageRecieved?.Invoke(this, args); if (MessageRecieved != null) { MessageRecieved.Invoke(this, args); } }
public void SendMessage(string message, ServerMessageTypeEnum type) { MessageRecieved?.Invoke(this, new ServerMessageRecievedEventArgs { Type = type, Message = message }); }
/// <summary> /// invokes the MessageRecieved event with the correct arguments /// </summary> /// <param name="message">message to write</param> /// <param name="type">type of message</param> public void Log(string message, MessageTypeEnum type) { MessageRecievedEventArgs e = new MessageRecievedEventArgs(); e.Message = message; e.Status = type; LogList.Add(e); MessageRecieved?.Invoke(this, e); }
/// <summary> /// Logs the specified message. /// </summary> /// <param name="message">The message to log.</param> /// <param name="type">The type of the message.</param> public void Log(string message, MessageTypeEnum type) { m_LogMessages.Add(new LogMessageRecord(message, type)); MessageRecievedEventArgs msgEventArgs = new MessageRecievedEventArgs(); msgEventArgs.Message = message; msgEventArgs.Status = type; MessageRecieved?.Invoke(this, msgEventArgs); }