private void Listen() { if (cancellationToken.IsCancellationRequested) { pipeStream.Close(); return; } byte[] pBuffer = new byte[BufferSize]; pipeStream.ReadAsync(pBuffer, 0, BufferSize, cancellationToken.Token).ContinueWith(t => { int ReadLen = t.Result; if (ReadLen == 0) { OnPipeClientClosed.Invoke(this, null); cancellationToken.Cancel(); pipeStream.Close(); return; } Listen(); OnMessageRecieved.Invoke(Encoding.UTF8.GetString(pBuffer, 0, ReadLen)); }); }
public void HandleMessage(string messageFromServer) { var messages = messageFromServer.Split(new[] { "<<EOFS>>" }, StringSplitOptions.RemoveEmptyEntries); foreach (var message in messages) { if (message.Length < 7) { continue; } XDocument xDoc = null; try { xDoc = XDocument.Parse(message); } catch (Exception e) { Console.WriteLine(e); } var rootName = xDoc?.Root?.Name.ToString(); switch (rootName) { case "stroke": OnStrokeRecieved?.Invoke(XmlConverter.GetStroke(xDoc)); break; case "message": OnMessageRecieved?.Invoke(XmlConverter.GetMessage(xDoc)); break; case "new_user": OnUserConnected?.Invoke(XmlConverter.GetUser(xDoc)); break; case "user_logout": OnUserLogout?.Invoke(XmlConverter.GetUser(xDoc)); break; case "users_list": OnUsersListReceived?.Invoke(XmlConverter.GetUsers(xDoc)); break; case "login_response": var user = XmlConverter.GetAuthResult(xDoc); if (string.IsNullOrEmpty(user)) { OnLoginFailure?.Invoke(); } else { OnLoginComplete?.Invoke(user); } break; default: break; } } }
public void Consume(string topic) { var consumerThread = new Thread(() => { var rand = new Random(); while (true) { int i = rand.Next(10); if (i >= 5) { var newUser = new User() { Firstname = "dg", Surname = " sdfg" }; OnMessageRecieved.Invoke(newUser as T); } else { OnConsumeError.Invoke(null); } } }); consumerThread.Start(); }
void ProccessMessage() { while (End != true) { if (Messageque.Count != 0) { IMQTTMessage message = null; var buffer = Messageque.Dequeue(); switch (ReadMessageTypeFromHeader(buffer[0])) { case MessageType.Connect: { ConnectMessage mess = new ConnectMessage(); mess.MakeMessage(buffer); message = mess; Console.WriteLine("Message connected"); Console.WriteLine("username:" + mess.UserName); break; } } OnMessageRecieved?.Invoke(message); } } }
void NotifyAboutAlreadyCollectedMessages() { for (int i = 0; i < messages.Count; i++) { OnMessageRecieved?.Invoke(GetInstance().messages[i]); } }
private void _Consume <T1>(string topic) { using (var c = new ConsumerBuilder <T1, string>(Config).Build()) { c.Subscribe(topic); try { while (true) { try { var cr = c.Consume(); var dMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <t3>(cr.Value); OnMessageRecieved?.Invoke(dMessage); // Console.WriteLine($"Consumed message '{cr.Value}' at: '{cr.TopicPartitionOffset}'."); } catch (ConsumeException e) { OnConsumeError?.Invoke(e); // Console.WriteLine($"Error occured: {e.Error.Reason}"); } } } catch (OperationCanceledException) { // Ensure the consumer leaves the group cleanly and final offsets are committed. c.Close(); } } }
void Update() { if (currMessage.Length > 0) { Debug.Log("Message recieved: " + currMessage); messageRecieved?.Invoke(currMessage); currMessage = string.Empty; } }
void Update() { if (currPacket.Length > 0) { Debug.Log("Message recieved: " + currPacket); messageRecieved.Invoke(currPacket); currPacket = null; } }
public void Send(int opCode, object args) { Task.Run(() => { //do some work Console.WriteLine("protocol: started working"); Thread.Sleep(5000); Console.WriteLine("protocol: work done"); OnMessageRecieved?.Invoke(this, new ProtocolMessage(OperationStatus.Finished)); }); }
public async Task Start(CancellationToken token = default) { bool retry = false; int retryCount = 0; do { try { irc = new TcpClient(AddressFamily.InterNetwork); await irc.ConnectAsync(server, port); token.ThrowIfCancellationRequested(); stream = irc.GetStream(); reader = new StreamReader(stream); writer = new StreamWriter(stream); } catch (OperationCanceledException) { return; } catch (Exception e) { Console.WriteLine(e.ToString()); Thread.Sleep(5000); retry = ++retryCount <= RetryLimit; } } while (retry); running = true; login(writer); writer.WriteLine($"JOIN #{channel}"); writer.Flush(); OnConnected?.Invoke(this, new ConnectedEventArgs(server, channel)); isStarted = true; while (running) { token.ThrowIfCancellationRequested(); string inputLine; while ((inputLine = await reader.ReadLineAsync()) != null) { string[] splits = inputLine.Split(' '); if (splits[0] == "PING") { pong(writer, splits.Skip(1)); } else { OnMessageRecieved?.Invoke(this, new MessageRecievedEventArgs(String.Join(" ", splits), channel)); } } } }
private void StartListening() { _isListening = true; _listeningThread = new Thread(() => { while (_isListening) { byte[] data = new byte[256]; Int32 bytes = _stream.Read(data, 0, data.Length); string message = System.Text.Encoding.ASCII.GetString(data, 0, bytes); OnMessageRecieved?.Invoke(message); } }); _listeningThread.Start(); }
void AddMessage(Message m) { switch (mode) { case LoggerMode.Collect: messages.Add(m); break; case LoggerMode.NotifcationAndCollect: messages.Add(m); OnMessageRecieved?.Invoke(m); break; case LoggerMode.NotificationNoCollect: OnMessageRecieved?.Invoke(m); break; } }
public void StartReadingAsync() { _readerSource = new CancellationTokenSource(); _readerToken = _readerSource.Token; _readerTask = new Task(() => { while (true) { string line = ReadAsync().Result; if (string.IsNullOrEmpty(line)) { continue; } Task.Run(() => OnMessageRecieved?.Invoke(this, line)).ConfigureAwait(false); } }, _readerToken); _readerTask.Start(); }
void Update() { if (websocket == null) { return; } if (currImages.Count > 0) { ImageMessage imageMessage = currImages[0]; ImageMessage imageCopy = imageMessage; messageRecieved?.Invoke(imageCopy); currImages.Remove(imageMessage); if (numLayers == 0) { messageComplete?.Invoke(); } } #if !UNITY_WEBGL || UNITY_EDITOR websocket.DispatchMessageQueue(); #endif }
private void NotifyMessageRecieved(string socketName, string message) => OnMessageRecieved?.Invoke(socketName, message);
public void RecieveMessage(Message message) { message.incoming = true; AddDecodedMessageToLog(message); OnMessageRecieved?.Invoke(message); //Gateway ready if (message.messageType == MessageType.C_INTERNAL && message.subType == (int)InternalDataType.I_GATEWAY_READY) { return; } //Gateway log message if (message.messageType == MessageType.C_INTERNAL && message.subType == (int)InternalDataType.I_LOG_MESSAGE) { return; } //New ID request if (message.nodeId == 255) { if (message.messageType == MessageType.C_INTERNAL && message.subType == (int)InternalDataType.I_ID_REQUEST) { if (enableAutoAssignId) { SendNewIdResponse(); } } return; } //Config request if (message.messageType == MessageType.C_INTERNAL && message.subType == (int)InternalDataType.I_CONFIG) { SendConfigResponse(message.nodeId); } //Sensor request if (message.messageType == MessageType.C_REQ) { ProceedRequestMessage(message); } //Gateway vesrion (alive) response if (message.nodeId == 0 && message.messageType == MessageType.C_INTERNAL && message.subType == (int)InternalDataType.I_VERSION) { if (gatewayState != GatewayState.Connected) { SetGatewayState(GatewayState.Connected); } } //request to node if (message.nodeId == 0) { return; } UpdateNodeFromMessage(message); UpdateSensorFromMessage(message); }
/// <summary> /// Listens to incoming messages and handles them. /// </summary> private void Listen() { Log.Info("Now listing"); // ------------------------------------------------------------------------------------------------------------ // Taken from https://stackoverflow.com/questions/10332630/connection-reset-on-receiving-packet-in-udp-server // ------------------------------------------------------------------------------------------------------------ // This ignores connection resets as errors. If this is not set and a client crashes then this throws exception // on the server. This is why the code beneath is there. I am not sure if could have just catched the error and // ignored it, but I feel like this is the most efficient way of doing it. Eventhough I don't really know why // the socket needs to be configured like that. const int SIO_UDP_CONNRESET = -1744830452; byte[] inValue = new byte[] { 0 }; byte[] outValue = new byte[] { 0 }; connection.Client.IOControl(SIO_UDP_CONNRESET, inValue, outValue); // ------------------------------------------------------------------------------------------------------------ // Start listing for messages connection.Client.Bind(new IPEndPoint(IPAddress.Any, port)); while (exitRequested == false) { // Listen for any messages. IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0); byte[] buffer; try { // Recieve the message. buffer = connection.Receive(ref endPoint); } catch (SocketException se) // Anything went wrong with the socket. { // Interrupts are okay. So if that did not occure print the error message if (se.SocketErrorCode != SocketError.Interrupted) { Console.WriteLine(se.ToString()); } continue; } catch (Exception ex) // catch any other exception that might occur { Console.WriteLine(ex.ToString()); continue; } if (buffer == null || buffer.Length == 0) { continue; } // If the connection is a new one, save it to the end points and send a welcome message. ConnectedClient connectedClient = null; for (int i = 0; i < connectedAdresses.Count; i++) { if (connectedAdresses[i].ip.Equals(endPoint)) { connectedClient = connectedAdresses[i]; } } bool isWelcomeMessage = IsWelcomeMessage(buffer); if (isWelcomeMessage == true && connectedClient != null) { continue; } if (connectedClient == null) { string response = Encoding.ASCII.GetString(buffer); if (response.Length < 6 || connectedAdresses.Count >= NetConstants.MAX_PLAYERS) { continue; } string name = response.Substring(6, response.Length - NetConstants.MAX_NAME_LENGTH - 6 > 0 ? NetConstants.MAX_NAME_LENGTH : response.Length - 6); byte id = NetUtils.GetLowestAvailableId(connectedAdresses); connectedAdresses.Add(connectedClient = new ConnectedClient(endPoint, name, id)); Send(connectedClient, Encoding.ASCII.GetBytes("Hello!")); NetManager.Instance.InvokePlayerConnected(connectedClient); continue; } OnMessageRecieved.Invoke(connectedClient, buffer); } }
public void OnMessage(object sender, Message msg) { var rTime = DateTime.Now; if (msg.XDelay != null && msg.XDelay.Stamp != null) { rTime = msg.XDelay.Stamp.ToLocalTime(); } switch (msg.Type) { case MessageType.normal: break; case MessageType.error: if (msg.Error != null && !String.IsNullOrWhiteSpace(msg.Error.ErrorText)) { OnMessageRecieved.Invoke(this, new NewUser(msg.From), msg.Error.ErrorText, DateTime.Now, Client.LobbyMessageType.Error); } break; case MessageType.chat: switch (msg.Chatstate) { case Chatstate.None: if (!IsGroupChat && !String.IsNullOrWhiteSpace(msg.Body) && OnMessageRecieved != null && Users.Contains(new NewUser(msg.From.Bare))) { OnMessageRecieved.Invoke(this, new NewUser(msg.From.Bare), msg.Body, rTime); } break; case Chatstate.active: break; case Chatstate.inactive: break; case Chatstate.composing: break; case Chatstate.gone: break; case Chatstate.paused: break; default: throw new ArgumentOutOfRangeException(); } break; case MessageType.groupchat: if (IsGroupChat && msg.Chatstate == Chatstate.None) { if (msg.From.Bare == GroupUser.User.Bare) { if (!String.IsNullOrWhiteSpace(msg.Subject)) { if (OnMessageRecieved != null) { OnMessageRecieved.Invoke(this, new NewUser( new Jid(msg.From.Resource + "@" + Skylabs.Lobby.Client.Host)), msg.Subject, rTime, Client.LobbyMessageType.Topic); } } else if (!String.IsNullOrWhiteSpace(msg.Body)) { if (OnMessageRecieved != null) { OnMessageRecieved.Invoke(this, new NewUser( new Jid(msg.From.Resource + "@" + Skylabs.Lobby.Client.Host)), msg.Body, rTime); } } } } break; case MessageType.headline: break; default: throw new ArgumentOutOfRangeException(); } }
void MessageRecieved(string username, string message) { OnMessageRecieved?.Invoke(username + " says " + message); }
private void ReadMessage(object sender, MessageEventArgs args) { var userId = args.Message.From.Id; var chatId = args.Message.Chat.Id; var message = args.Message.Text; chatIds[userId] = chatId; if (message == null) { bot.SendTextMessageAsync(chatId, "Я не понимаю. Напиши словами, плес"); } else { DateTime date = default; string text = ""; int number = 0; bool isBackward = false; bool isShowThisItem = false; var expecting = GetExpecting(userId); var expectingFormat = expecting.Item1; var expectingRange = Tuple.Create(expecting.Item2, expecting.Item3); if (GetStringWithoutOpeningSlash(message).ToLower() == "back") { isBackward = true; OnMessageRecieved?.Invoke(userId, date, text, number, isBackward, isShowThisItem); return; } switch (expectingFormat) { case ExpectingRequestFormat.FirstRequest: isShowThisItem = true; break; case ExpectingRequestFormat.Text: text = message; break; case ExpectingRequestFormat.DateTime: { var isDateTime = DateTime.TryParse(message, out var dateTime); if (!isDateTime) { bot.SendTextMessageAsync(chatId, "Некорректный формат даты.\nПопробуйте ДД-ММ-ГГГГ ЧЧ:ММ\n/Back"); return; } date = dateTime; break; } case ExpectingRequestFormat.OnlyDayDateTime: { var isDateTime = DateTime.TryParse(message, out var dateTime); if (!isDateTime) { bot.SendTextMessageAsync(chatId, "Некорректный формат даты.\nПопробуйте ДД-ММ-ГГГГ\n/Back"); return; } date = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day); break; } case ExpectingRequestFormat.Number: message = GetStringWithoutOpeningSlash(message); var isInt = int.TryParse(message, out var outNumber); if (!isInt || outNumber < expectingRange.Item1 || outNumber > expectingRange.Item2) { bot.SendTextMessageAsync(chatId, "Неверное число\n/Back"); return; } number = outNumber; break; case ExpectingRequestFormat.OnlyTimeDateTime: { var isDateTime = DateTime.TryParse(message, out var dateTime); if (!isDateTime) { bot.SendTextMessageAsync(chatId, "Некорректный формат времени.\nПопробуйте ЧЧ:ММ\n/Back"); return; } date = dateTime; break; } } OnMessageRecieved?.Invoke(userId, date, text, number, isBackward, isShowThisItem); } }
public void RecieveMessage(IMessage message) { OnMessageRecieved?.Invoke(message); }
public void Produce(string message) { OnMessageRecieved.Invoke(message); }
private void ReadMessages() { client.ReceiveBufferSize = Int32.MaxValue; Console.WriteLine("started reading mesgeges"); while (isConnected) { try { if (!networkStream.DataAvailable) { continue; } byte[] byteForm = new byte[HEADER_SIZE]; networkStream.Read(byteForm, 0, HEADER_SIZE); string headerMsg = Encoding.Default.GetString(byteForm, 0, HEADER_SIZE).Trim('\0'); Header header = JsonConvert.DeserializeObject <Header>(headerMsg); if (header.messageType == MessageType.PollMessage) { continue; } int amount = header.size; string typeName = header.messageType.ToString(); byte[] contentByteForm = new byte[amount]; int bytesRead = 0; string totalData = ""; int chunkSize = amount; while (true) { byte[] imageChunk = new byte[chunkSize]; networkStream.Read(imageChunk, 0, chunkSize); string chunkStr = Encoding.Default.GetString(imageChunk, 0, chunkSize).Trim('\0'); totalData += chunkStr; bytesRead += chunkStr.Length; if (totalData.Length < amount) { chunkSize = amount - totalData.Length; } else { break; } } string messageContentString = totalData; Message msg = MessageParser.FromJson <Message>(messageContentString); Runner.Primary(() => OnMessageRecieved?.Invoke(msg, header.messageType)); } catch (MessageParseException ex) { Console.WriteLine(ex.ToString()); // throw new CorruptDataException("Data corrupt"); //invoke OnMessageParseException?.Invoke(ex); break; } catch (Exception ex) { Console.WriteLine(ex.ToString()); break; } finally { networkStream.Flush(); } } Disconnect(); }