private async void DefaultMessageProcess(HttpResponseMessage message) { //TODO 还有好多要DO的……这里 HttpContent content = message.Content; string str = await content.ReadAsStringAsync(); if (string.IsNullOrWhiteSpace(str)) { return; } JsonDocument jsonDocument = JsonDocument.Parse(str); JsonElement json = jsonDocument.RootElement; try { int i = json.GetArrayLength(); for (int j = 0; j < i; ++j) { string strJson = json[0].ToString(); Request request = EntityClass.FromJson(strJson, typeof(Request)) as Request; var db = Database.Util.GetInstance(); db.Add(request); ReceiveMessage?.Invoke(request); //触发网络信息接收事件? DateTime time = request.Request_Time.AddSeconds(1); Util.AppendFile(Program.INFO_FILE, $"{time}\n"); } } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// Cria o objeto consumidor /// </summary> private void InitializeObject(bool durable = true, bool exclusive = false, bool autoDelete = false, IDictionary <string, object> arguments = null, bool queueDeclare = false) { if (queueDeclare) { Channel.QueueDeclare(QueueName, durable: durable, exclusive: exclusive, autoDelete: autoDelete, arguments: arguments); } var consumer = new EventingBasicConsumer(Channel); consumer.Received += (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var data = JsonConvert.DeserializeObject <T>(message); ReceiveMessage?.Invoke(data, ea.DeliveryTag); } catch (Exception ex) { //ex.QueueMessage = Encoding.UTF8.GetString(ea.Body); //ex.QueueType = typeof(T); OnReceiveMessageException?.Invoke(ex, ea.DeliveryTag); } }; Channel.BasicQos(0, _prefetchCount, false); Channel.BasicConsume(queue: QueueName, autoAck: _autoAck, consumer: consumer); }
private void ReceiveMessageCallback(IAsyncResult result) { try { var endPoint = UdpSocket.Any(); lock (_disposeLock) { if (_disposed) { return; } _socket.EndReceiveFrom(result, ref endPoint); } var message = DeserializeMessage(UdpSocket.BufferFor(result)); if (message != null) { message.Origin = (IPEndPoint)endPoint; ReceiveMessage?.Invoke(this, new MessageEventArgs(message)); } } catch (ObjectDisposedException) { return; } catch (Exception e) { RaiseMessagerException(e); } BeginReceiveMessage(); }
/// <summary> /// Called when a message from a client is received. /// </summary> /// <param name="e">Metadata and the message from client</param> protected override void OnMessage(MessageEventArgs e) { if (_session == null) { byte[] clientPublicKey = null; var messageEncryptionCookie = Context.CookieCollection["MessageEncryption"]; if (messageEncryptionCookie?.Value == "1") { var shakeHandsCookie = Context.CookieCollection["ShakeHands"]; clientPublicKey = Convert.FromBase64String( shakeHandsCookie.Value); } _session = _server.SessionRepository.CreateSession( clientPublicKey, _server, this); _session.BeforeDispose += BeforeDisposeSession; } else { ReceiveMessage?.Invoke(e.RawData); } }
private void Listen() { var buffer = new byte[1024 * 10]; while (tcpClient.Connected) { try { var length = stream.Read(buffer, 0, buffer.Length); if (length > 0) { var data = buffer.Take(length).ToArray(); ReceiveMessage?.Invoke(this, data); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } ClientDisconned?.Invoke(this); stream.Close(); tcpClient.Close(); }
private async Task <HubConnection> ConnectionAsync() { int reConnectionCount = 0; while (true) { var HubConnection = new HubConnectionBuilder() .WithUrl(baseUri) .WithConsoleLogger() .Build(); try { HubConnection.On <string> ("Reply", (Result) => { ReplyContent result = PublicMethod.JsonDeSerialize <ReplyContent> (Result); switch (result.ReplyMethodName) { case ReplyMethodName.Connection: HubToken = result.Content; break; case ReplyMethodName.Subscribe: GroupList.Add(result.Content); break; case ReplyMethodName.DeSubscribe: GroupList.Remove(result.Content); break; default: break; } }); HubConnection.On <string> ("Send", (content) => { if (ReceiveMessage != null) { ReceiveMessage.Invoke(this, new ReceiveEventArgs(PublicMethod.JsonDeSerialize <SendContent> (content))); } }); await HubConnection.StartAsync(); await awaitHubtoken(); return(HubConnection); } catch (Exception e) { reConnectionCount++; if (reConnectionCount >= 3) { CommunicationError(this, new ErrorEventArgs(true, e.ToString())); return(HubConnection); } await Task.Delay(5000); } } }
public GroupService() { connection = new HubConnectionBuilder() .WithUrl("http://localhost:5000/GroupHub") .Build(); connection.Closed += HandleConnectionClosedAsync; connection.On <string, string>(nameof(IGroupClient.ReceiveMessage), (groupName, message) => { ReceiveMessage?.Invoke(groupName, message); }); }
/// <summary> /// Invoked on the background thread. /// </summary> /// <exception cref="SerializationException">An object in the graph of type parameter <typeparamref name="TRead"/> is not marked as serializable.</exception> private void ReadPipe() { while (IsConnected && _streamWrapper.CanRead) { var obj = _streamWrapper.ReadObject(); if (obj == null) { CloseImpl(); return; } ReceiveMessage?.Invoke(this, obj); } }
private void ReadStream() { while (_streamWrapper.CanRead) { var obj = _streamWrapper.ReadObject(); ReceiveMessage?.Invoke(this, obj); if (obj != null) { continue; } CloseImpl(); return; } }
private void ReceiveMessageCallback(IAsyncResult result) { try { var endPoint = UdpSocket.Any(); lock (_disposeLock) { if (_disposed) { return; } _socket.EndReceiveFrom(result, ref endPoint); } var message = DeserializeMessage(UdpSocket.BufferFor(result)); if (message != null) { message.Origin = (IPEndPoint)endPoint; int port; int bufferSize; if (IsValidTcpMessage(message, out port, out bufferSize)) { // switch to TCP mode to handle big messages TcpClient.Queue(message.Origin.Address, port, bufferSize, buffer => { var originalMessage = DeserializeMessage(buffer); originalMessage.Origin = message.Origin; ReceiveMessage?.Invoke(this, new MessageEventArgs(originalMessage)); }); } else { ReceiveMessage?.Invoke(this, new MessageEventArgs(message)); } } } catch (ObjectDisposedException) { return; } catch (Exception e) { RaiseMessagerException(e); } BeginReceiveMessage(); }
/// <summary> /// 消费线程 /// </summary> private void ConsumerMsg() { try { KafkaSub(); using (KafkaSubscribe) { while (runFlag) { try { ConsumeResult <string, string> consume; try { consume = KafkaSubscribe.Consume(); } catch (Exception e) { Logger.Log.Warn(true, string.Concat("组编号", _GroupId, ",主题", string.Join(",", _topic), "消息队列获取消息失败", e.Message, e.StackTrace)); continue; } if (consume.IsPartitionEOF) { Console.WriteLine($"到达主题 {consume.Topic}底部, 分区 {consume.Partition}, 偏移量 {consume.Offset}."); continue; } ReceiveMessage?.Invoke(consume.Message); } catch (ThreadInterruptedException) { break; } catch (ConsumeException e) { Logger.Log.Warn(true, string.Concat("组编号", _GroupId, ",主题", string.Join(",", _topic), "消息队列获取消息失败", e.Message, e.StackTrace)); } } } } catch (Exception e) { try { KafkaSubscribe.Close(); } catch { } Logger.Log.Warn(true, string.Concat("组编号", _GroupId, ",主题", string.Join(",", _topic), "消息队列获取消息失败", e.Message, e.StackTrace)); } }
private void OnMessageReceive(WebNotifyConnection client, MemoryStream stream) { stream.Position = 0; var property = (string)null; var type = (Type)null; var serializer = JsonSerializer.Create(jsonSettings); using (var reader = new StreamReader(stream)) using (var jreader = new JsonTextReader(reader)) { while (jreader.Read()) { switch (jreader.TokenType) { case JsonToken.PropertyName: property = (string)jreader.Value; break; case JsonToken.String: switch (property) { case ("Type"): type = TypeHelper.ParseType((string)jreader.Value); break; } break; case JsonToken.StartObject: if (property == "Value" && type != null) { property = null; var obj = serializer.Deserialize(jreader, type); if (obj is WebNotifyRegistration data) { client.Platform = data.Platform; client.Application = data.Application; client.Version = data.Version; return; } } break; } } } var message = Encoding.UTF8.GetString(stream.ToArray()); ReceiveMessage?.Invoke(this, new WebNotifyEventArgs(client, message)); }
protected virtual async Task <object> OnMessageReceive(WebNotifyConnection connection, MemoryStream stream) { await Task.Delay(10).ConfigureAwait(false); object obj = LoadMessage(connection, stream); if (obj is WebNotifyRegistration registration) { connection.Platform = registration.Platform; connection.Application = registration.Application; connection.Version = registration.Version; connection.VersionValue = Version.TryParse(connection.Version, out var version) ? version : new Version("1.0.0.0"); } ReceiveMessage?.Invoke(this, new WebNotifyEventArgs(connection, obj)); return(obj); }
private void ReadMessagesAsync() { while (Connecting || Connected) { try { string message = inputStream.ReadLine(); ReceiveMessage?.Invoke(this, new IrcMessageEventArgs(message)); } catch { StateChange?.Invoke(this, new IrcChangedEventArgs(IrcStates.Disconnected)); Connected = false; Connecting = false; } } }
public override void OnReceive(Context context, Intent intent) { if (SmsReceived.Equals(intent.Action)) { var bundle = intent.Extras; if (bundle != null) { var pdus = (Java.Lang.Object[])bundle.Get("pdus"); var messages = new SmsMessage[pdus.Length]; for (var i = 0; i < pdus.Length; i++) { #pragma warning disable 618 messages[i] = SmsMessage.CreateFromPdu((byte[])pdus[i]); #pragma warning restore 618 } if (messages.Length > 0) { var msgBody = new StringBuilder(); foreach (var smsMessage in messages) { if (smsMessage?.MessageBody != null) { msgBody.Append(smsMessage.MessageBody); } } //var msgAddress = messages[0].OriginatingAddress; var msgDate = messages[0].TimestampMillis; var saltBytes = AesEncryptamajig.GenerateSalt(); var messageAesPassword = PreferenceManager.GetDefaultSharedPreferences(context) .All["PrefMessageAesPassword"] as string; var content = AesEncryptamajig.Encrypt(msgBody.ToString(), messageAesPassword, saltBytes); ReceiveMessage?.Invoke(this, new MessageEventArgs(new Message { Salt = Convert.ToBase64String(saltBytes), Content = content, MessageTime = Utils.FromUnixTime(msgDate) })); } } } }
/// <summary> /// Invoked on the background thread. /// </summary> /// <exception cref="SerializationException">An object in the graph of type parameter <typeparamref name="TRead"/> is not marked as serializable.</exception> private void ReadPipe() { while (IsConnected && _streamWrapper.CanRead) { try { var obj = _streamWrapper.ReadObject(); if (obj == null) { CloseImpl(); return; } ReceiveMessage?.Invoke(this, obj); } catch { //we must ignore exception, otherwise, the named pipe wrapper will stop work. } } }
private void receive(IAsyncResult ar) { AsyncObject ao = (AsyncObject)ar.AsyncState; int recvBytes = 0; try { recvBytes = ao.WorkingSocket.EndReceive(ar); } catch (Exception ex) { ClientError?.Invoke(new ClientErrorEventArgs(ex, DateTime.Now, this)); return; } if (recvBytes > 0) { byte[] msgByte = new byte[recvBytes]; Array.Copy(ao.Buffer, msgByte, recvBytes); Message msg = new Message(msgByte); ReceiveMessage?.Invoke(new MessageEventArgs(msg, ao.WorkingSocket)); } try { ao.WorkingSocket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnReceive, ao); } catch (Exception ex) { ClientError?.Invoke(new ClientErrorEventArgs(ex, DateTime.Now, this)); return; } }
private void _CurrentProcess_OutputDataReceived(object sender, DataReceivedEventArgs e) { try { if (!string.IsNullOrEmpty(e?.Data)) { var message = Newtonsoft.Json.JsonConvert.DeserializeObject <MessageExchange.MessageInfo>(e.Data); _OutPutMessage.Add(message); ReceiveMessage?.Invoke(this, message); } } catch (Exception ex) { StopApp(); var message = new MessageExchange.MessageInfo { Text = e.Data, Time = DateTime.Now, Type = MessageExchange.MessageType.exception }; _OutPutError.Add(message); ReceiveError?.Invoke(this, message); } }
/// <summary> /// 异步接收 /// </summary> private void ReceiveAsync() { if (isClose) { return; } // if (NetworkStream != null) //{ System.Threading.ThreadPool.QueueUserWorkItem(obj => { try { while (!((tcpClient.Client.Poll(500, SelectMode.SelectRead) && (tcpClient.Client.Available == 0)) || !tcpClient.Client.Connected)) { System.Threading.Thread.Sleep(500); try { if (ReceiveMessage != null) { var message = new Message(); if (this.LineOff == null) { this.LineOff = (int)'\n'; } var iChar = -1; using (MemoryStream memoryStream = new MemoryStream()) { while ((iChar = NetworkStream.ReadByte()) > 0) { memoryStream.WriteByte((byte)iChar); if (iChar == this.LineOff) { break; } } message.Content = memoryStream.ToArray(); } if (message.Content == null && message.Content.Length > 0) { continue; } ("接收到数据:" + message.Content).WriteToLog(log4net.Core.Level.Info); message.NetworkStream = NetworkStream; if (System.Threading.SynchronizationContext.Current != null) { System.Threading.SynchronizationContext.Current.Post(callback => { ReceiveMessage?.Invoke(message); }, message); } else { ReceiveMessage?.Invoke(message); } } } catch (Exception ex) { ex.ToString(); } } ; } catch (Exception ex) { ex.ToString(); } Close(); Connection(); }); }
protected virtual Task <MessageProcessInstruction> OnReceiveMessage(string routingKeyOrQueueName, string consumerTag, long firstErrorTimestamp, string exchange, string message, string messageAdditionalInfo) { return(ReceiveMessage?.Invoke(routingKeyOrQueueName, consumerTag, firstErrorTimestamp, exchange, message, messageAdditionalInfo)); }
internal void receiveMessage(string message) { ReceiveMessage?.Invoke(message); //_接收.Add(s); }
/// <summary> /// Метод вызова события о приеме нового сообщения /// </summary> /// <param name="client_id">ID сокета клиента</param> /// <param name="value">Принятые данные</param> private void CallReceive(IntPtr client_id, byte[] value) { Task.Factory.StartNew(() => { ReceiveMessage?.Invoke(this, new Arguments.ReceiveServerArgs(client_id, value, StringEcncoding)); }); }
public void OnReceiveMessage(MessageDelegateArgs args) { ReceiveMessage?.Invoke(this, args); }
/// <summary> /// Event procedure: Called when a message from server is received. /// </summary> /// <param name="sender">Sender of the event</param> /// <param name="e">Event arguments containing the message content</param> private void OnMessage(object sender, MessageEventArgs e) { ReceiveMessage?.Invoke(e.RawData); }
/// <summary> /// /// </summary> /// <param name="o"></param> private void Acceptor(IAsyncResult o) { TcpListener server = o.AsyncState as TcpListener; try { TcpClient client = server.EndAcceptTcpClient(o); System.Threading.ThreadPool.QueueUserWorkItem(obj => { var ns = client.GetStream(); try { do { try { System.Threading.Thread.Sleep(1); var message = new Message(); if (this.LineOff == null) { this.LineOff = (int)'\n'; } var iChar = -1; using (MemoryStream memoryStream = new MemoryStream()) { while ((iChar = ns.ReadByte()) > 0) { memoryStream.WriteByte((byte)iChar); if (iChar == this.LineOff) { break; } } message.Content = memoryStream.ToArray(); } if (message.Content == null && message.Content.Length > 0) { continue; } ("接收到数据:" + message.Content).WriteToLog(log4net.Core.Level.Info); message.NetworkStream = ns; if (System.Threading.SynchronizationContext.Current != null) { System.Threading.SynchronizationContext.Current.Post(callback => { ReceiveMessage?.Invoke(message); }, message); } else { ReceiveMessage?.Invoke(message); } } catch (Exception ex) { ex.ToString(); } } while (!((client.Client.Poll(500, SelectMode.SelectRead) && (client.Client.Available == 0)) || !client.Client.Connected)); ("客户端<" + (client.Client.RemoteEndPoint as IPEndPoint).Address.ToString() + ">已断开!").WriteToLog(log4net.Core.Level.Info); } catch (Exception ex) { ("服务器监听异常,异常信息:" + ex.ToString()).WriteToLog(log4net.Core.Level.Error); } finally { //ms.Close(); //ms.Dispose(); //ms = null; ns.Close(); ns.Dispose(); ns = null; Close(client); } }); } catch (Exception ex) { ("服务器监听异常,异常信息:" + ex.ToString()).WriteToLog(log4net.Core.Level.Error); } finally { try { IAsyncResult result = server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server); } catch (Exception ex) { ("服务器监听异常停止,异常信息:" + ex.ToString()).WriteToLog(log4net.Core.Level.Error); } } }
private void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e) { Model.User user; Telegram.Bot.Types.Message message = e.Message; if (message != null && message.Type == MessageType.Text) { IQueryable <Model.User> users = _db.Users.Where((u) => u.TelegramId == message.From.Id); if (users.Count() > 0) { user = users.FirstOrDefault(); user.UserName = message.From.Username; user.FirstName = message.From.FirstName; user.LastName = message.From.LastName; //lock (_lockObj) //{ // _uiContext.Send(async (obj) => // { // _db.Users.Update(user); // await _db.SaveChangesAsync(); // }, null); //} _uiContext.Send((obj) => { _db.Users.Update(user); _db.SaveChanges(); }, null); } else { user = new Model.User() { TelegramId = message.From.Id, UserName = message.From.Username, FirstName = message.From.FirstName, LastName = message.From.LastName, Date = DateTime.Now }; //lock (_lockObj) //{ // _uiContext.Send(async (obj) => // { // _db.Users.Add(user); // await _db.SaveChangesAsync(); // }, null); //} _uiContext.Send((obj) => { _db.Users.Add(user); _db.SaveChanges(); }, null); } //if (user == null) //{ // user = new Model.User() // { // TelegramId = message.From.Id, // UserName = message.From.Username, // FirstName = message.From.FirstName, // LastName = message.From.LastName, // Date = DateTime.Now // }; // await _db.Users.AddAsync(user); //} //else //{ // _db.Users.Update(user); //} Model.Message messageDb = new Model.Message() { UserId = user.Id, MessageId = message.MessageId, ChatId = message.Chat.Id, Text = message.Text, Date = message.Date }; //lock (_lockObj) //{ // _uiContext.Send(async (obj) => // { // _db.Messages.Add(messageDb); // await _db.SaveChangesAsync(); // }, null); //} _uiContext.Send((obj) => { _db.Messages.Add(messageDb); _db.SaveChanges(); }, null); ReceiveMessage?.Invoke(this, new object[] { message.Chat.Id, message.Text }); } }
/// <summary> /// Событие о получении новых данных /// </summary> /// <param name="value">полученные данные от сервера</param> internal void CallReceive(byte[] value) { Task.Factory.StartNew(() => { ReceiveMessage?.Invoke(this, new ReceiveClientArgs(value, StringEcncoding)); }); }
public static void OnReceiveMessage(ChatMessage chatMessage) { ReceiveMessage?.Invoke(chatMessage); }
/// <summary> /// Метод вызова события о приеме нового сообщения /// </summary> /// <param name="client_id">ID сокета клиента</param> /// <param name="value">Принятые данные</param> private void CallReceive(EndPoint point, byte[] value) { Task.Factory.StartNew(() => { ReceiveMessage?.Invoke(this, new Arguments.ReceiveServerArgs(point, value, StringEcncoding)); }); }
/// <summary> /// Message received /// </summary> /// <param name="obj">object</param> /// <param name="database">database index</param> private void OnReceiveMessage(T obj, int database) { //Event invoker ReceiveMessage?.Invoke(obj, database); }