protected override async Task MessageReceived(IDialogContext context, IAwaitable <Message> item) { var msg = await item; this.message = new PartialMessage { Text = msg.Text }; await base.MessageReceived(context, item); }
// This handles a receive event on a particular client socket that has // connected. We read data from them and collect it into a string builder // for use later. public void ReadCallback(IAsyncResult ar) { try { // From the state of the event, get our the state object that wraps all // of the information for this client, and then get the socket out of // it. BuildClient client = (BuildClient)ar.AsyncState; Socket socket = client.socket; // Perform the actual receive now; the result is the number of bytes // read, which can conceivably be 0; we only need to worry about doing // something if we actually got some data. int bytesRead = socket.EndReceive(ar); if (bytesRead == 0) { Console.WriteLine("Client closed connection"); return; } // Console.WriteLine("==> Read {0} bytes", bytesRead); int bytesUsed = 0; while (bytesUsed != bytesRead) { // Give some bytes to the current partial message so it can // reconstruct itself. bytesUsed += inMsg.GiveBytes(client.readBuffer, bytesRead, bytesUsed); // If this message is complete, then echo it back to the other end // and get ready for another received message. if (inMsg.IsComplete()) { client.Dispatch(inMsg); inMsg = new PartialMessage(); } } // End by getting ready to read more data. client.BeginReading(); } catch (SocketException se) { Console.WriteLine("Socket Error: {0}", se.Message); Console.WriteLine("Closing connection"); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
protected override async Task MessageReceived(IDialogContext context, IAwaitable <IMessageActivity> item) { try { var msg = await item; this.LUISmessage = new PartialMessage { Text = msg.Text }; await base.MessageReceived(context, item); } catch (Exception ex) { await context.PostAsync(ex.Message); } }
internal void ReceivePartialMessage(PartialMessage message) { var queue = this.partials.GetOrAdd(message.OriginalMessageId, id => new ConcurrentQueue <PartialMessage>()); queue.Enqueue(message); if (queue.Count != message.Count) { return; } if (!this.partials.TryRemove(message.OriginalMessageId, out queue)) { return; } byte[] payload = new byte[queue.Sum(p => p.Payload.Length)]; int offset = 0; foreach (PartialMessage msg in queue.OrderBy(p => p.Header.MessageId)) { byte[] partialPayload = msg.Payload; Buffer.BlockCopy(partialPayload, 0, payload, offset, partialPayload.Length); offset += partialPayload.Length; } MessageSerializer srlzr = this.serializer; if (srlzr == null) { return; } List <Message> messages = srlzr.BufferMessages(payload); if (messages != null && messages.Count == 1) { Receive(messages[0], fromPartials: true); } else { DisconnectAsync(); } }
//internal BasicLuisDialog() { } protected override async Task MessageReceived(IDialogContext context, IAwaitable <Microsoft.Bot.Connector.IMessageActivity> item) { var msg = await item; if (string.IsNullOrEmpty(context.UserData.Get <string>(SPAccessTokenKey))) { MicrosoftAppCredentials cred = new MicrosoftAppCredentials( ConfigurationManager.AppSettings["MicrosoftAppId"], ConfigurationManager.AppSettings["MicrosoftAppPassword"]); StateClient stateClient = new StateClient(cred); BotState botState = new BotState(stateClient); BotData botData = await botState.GetUserDataAsync(msg.ChannelId, msg.From.Id); context.UserData.SetValue <string>(SPAccessTokenKey, botData.GetProperty <string>(SPAccessTokenKey)); } this.message = new PartialMessage { Text = msg.Text }; await base.MessageReceived(context, item); }
public static IPartialMessage ToPartialMessage(this IMessage message) { var msg = new PartialMessage { Activity = message.Activity, Application = message.Application, ApplicationID = message.ApplicationID, Attachments = new Optional <IReadOnlyList <IAttachment> >(message.Attachments), Author = new Optional <IUser>(message.Author), ChannelID = message.ChannelID, Components = message.Components, Content = message.Content, EditedTimestamp = message.EditedTimestamp, Embeds = new Optional <IReadOnlyList <IEmbed> >(message.Embeds), Flags = message.Flags, GuildID = message.GuildID, ID = message.ID, Interaction = message.Interaction, IsPinned = message.IsPinned, IsTTS = message.IsTTS, Member = message.Member, MentionedChannels = message.MentionedChannels, MentionedRoles = new Optional <IReadOnlyList <Snowflake> >(message.MentionedRoles), Mentions = new Optional <IReadOnlyList <IUserMention> >(message.Mentions), MentionsEveryone = message.MentionsEveryone, MessageReference = message.MessageReference, Nonce = message.Nonce, Reactions = message.Reactions, ReferencedMessage = message.ReferencedMessage, StickerItems = message.StickerItems, Thread = message.Thread, Timestamp = message.Timestamp, Type = message.Type, WebhookID = message.WebhookID }; return(msg); }
/// <summary> /// Reassembles a segmented byte array. /// </summary> /// <param name="packet">Array segment.</param> /// <param name="message">Full array, null if incomplete.</param> /// <returns>Message fully desegmented, "message" is assigned.</returns> public byte[] Desegment(byte[] packet) { ulong steamId = BitConverter.ToUInt64(packet, 0); if (steamId != SteamId) { return(null); } int hash = BitConverter.ToInt32(packet, sizeof(ulong)); int packetId = BitConverter.ToInt32(packet, sizeof(int) + sizeof(ulong)); var dataBytes = new byte[packet.Length - META_SIZE]; Array.Copy(packet, META_SIZE, dataBytes, 0, packet.Length - META_SIZE); if (!messages.ContainsKey(hash)) { if (packetId == 0) { return(dataBytes); } messages.Add(hash, new PartialMessage(packetId)); } PartialMessage message = messages[hash]; message.WritePart(packetId, dataBytes); if (message.IsComplete) { messages.Remove(hash); return(message.Data); } return(null); }
/// <summary> /// Invoked every time a message is received from the client. This does all /// of the protocol handling work on our end, handling messages as /// appropriate. /// </summary> private void Dispatch(PartialMessage inMsg) { try { // Convert the message from it's partial data format into a complete // message. IProtocolMessage message = inMsg.getMessage(); Console.WriteLine("Recv: {0}", message); // If we have not been introduced to the other end of the connection yet // then trigger an error unless this message is the introduction message // itself. if (hasIntroduced == false && message.MsgID != MessageType.Introduction) { ProtocolViolationMessage(message, "First message must be an introduction"); return; } switch (message.MsgID) { // These messages are only valid when transmitted from the server to // the client; if the client sends them to us, issue a protocol // violation. case MessageType.Message: case MessageType.Error: case MessageType.Acknowledge: case MessageType.BuildOutput: case MessageType.BuildComplete: ProtocolViolationMessage(message, "These messages are for server use only"); break; // This should always be the first message received on a connection // (and is only valid as the first message). It has specific // handling associated with it. case MessageType.Introduction: HandleIntroduction(message as IntroductionMessage); break; // The client is indicating that it's time to set up a new build. // This message tells us what paths are being built so that we can // set things up on our end. case MessageType.SetBuild: HandleSetBuild(message as SetBuildMessage); break; // The client is sending us the contents of a file. We need to // persist it to disk so that it can take a part in the build. case MessageType.FileContent: HandleFileContents(message as FileContentMessage); break; // Handle the command to execute a build by running the given // command inside of the appropriate folder, dispatching all of // the output back to the other end. case MessageType.ExecuteBuild: HandleExecuteBuild(message as ExecuteBuildMessage); break; default: throw new Exception("Unknown message type"); } } catch (Exception err) { SendError(true, 9998, "Server Exception: {0}", err.Message); } }
protected Task <bool> SendCore(Message message, bool dontSetId, bool responseRequested, int timeout, out Task <Message> responseTask) { if (message == null) { throw new ArgumentNullException("message"); } responseTask = null; Socket sock = this.socket; MessageSerializer mserialzier = this.serializer; TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool> (message); if (sock == null || mserialzier == null || (!IsConnected && !IsConnecting)) { tcs.TrySetResult(false); if (responseRequested) { var responseTcs = new TaskCompletionSource <Message>(); responseTcs.SetCanceled(); responseTask = responseTcs.Task; } return(tcs.Task); } if (message.Header == null) { message.Header = new MessageHeader(); } if (!dontSetId) { SetMessageId(message); if (responseRequested) { responseTask = Responses.SendFor(message, tcs.Task, timeout); } } IPEndPoint endPoint = IPEndPoint; if (endPoint == null) { tcs.SetResult(false); return(tcs.Task); } SocketAsyncEventArgs e; BufferPool.TryGetBuffer(out e); int length; byte[] buffer = mserialzier.GetBytes(message, out length, e.Buffer); if (!(message is PartialMessage) && length > 490) { byte count = (byte)Math.Ceiling((length / 490f)); int i = 0; int remaining = length; do { int payloadLen = Math.Min(490, remaining); var partial = new PartialMessage { OriginalMessageId = (ushort)message.Header.MessageId, Count = count, Header = new MessageHeader() }; partial.SetPayload(buffer, i, payloadLen); if (i == 0) // We have to fill the gap the original id uses for reliability { partial.Header.MessageId = message.Header.MessageId; } else { SetMessageId(partial); } lock (this.pendingAck) this.pendingAck.Add(partial.Header.MessageId, new Tuple <DateTime, Message> (DateTime.UtcNow, partial)); mserialzier.GetBytes(partial, out length, e.Buffer); e.SetBuffer(0, length); e.RemoteEndPoint = endPoint; remaining -= payloadLen; i += payloadLen; if (remaining == 0) { e.Completed += OnSendCompleted; e.UserToken = tcs; } else { e.Completed += OnPartialSendCompleted; } try { this.lastReliableSendActivity = Stopwatch.GetTimestamp(); if (!sock.SendToAsync(e)) { if (remaining == 0) { OnSendCompleted(this, e); } else { OnPartialSendCompleted(this, e); } } } catch (ObjectDisposedException) { BufferPool.PushBuffer(e); if (remaining == 0) { CleanupSend(e); } else { CleanupPartialSend(e); } tcs.TrySetResult(false); } if (remaining > 0) { BufferPool.TryGetBuffer(out e); } } while (remaining > 0); } else { e.SetBuffer(0, length); e.RemoteEndPoint = endPoint; e.Completed += OnSendCompleted; e.UserToken = tcs; if (message.PreferReliable || message.MustBeReliable) { this.lastReliableSendActivity = Stopwatch.GetTimestamp(); lock (this.pendingAck) this.pendingAck.Add(message.Header.MessageId, new Tuple <DateTime, Message> (DateTime.UtcNow, message)); } try { if (!sock.SendToAsync(e)) { OnSendCompleted(this, e); } } catch (ObjectDisposedException) { CleanupSend(e); tcs.TrySetResult(false); } } return(tcs.Task); }
public void OnEvent(PublishData data, long sequence, bool endOfBatch) { var messageEvent = data; if (messageEvent == null || messageEvent.ListOutput == null) { return; } foreach (var publishMsg in messageEvent.ListOutput) { if (publishMsg.Message is IControler) { //neu la connect message if (publishMsg.Message is ConnectMessage) { var connectMsg = publishMsg.Message as ConnectMessage; if (connectMsg.StartupMessage != null) { //thuc hien Marshal messase check AutoUpdate var str = JsonUtils.SerializeMessage(connectMsg.StartupMessage); connectMsg.BytesMsg = EncodingUtils.GetBytes(str); publishMsg.Message = connectMsg; } } } else if (publishMsg.Message is IMessage) { if (publishMsg.Message is GetStartupMemoryRequest && _loader != null) { var req = publishMsg.Message as GetStartupMemoryRequest; _loader.ProcessData(ref req); } else { var message = publishMsg.Message as IMessage; publishMsg.IsSendToQueue = message.IsSendToQueue; var jsonStr = JsonUtils.SerializeMessage(message); if (message is Response && jsonStr.Length > _maxSize) { //chi thuc hien chia nho khi msg la response va kich thuoc lon hon kich thuc cho phep List <string> arr = Split(jsonStr, _maxSize); int count = arr.Count; publishMsg.BytesMsg = new List <byte[]>(); for (int i = 0; i < count; i++) { var msg = new PartialMessage() { Count = count, Index = i, MainRequestKey = (message as Response).RequestKey, RawMessage = arr[i], SendingTopic = message.SendingTopic, MainMsgType = message.GetType().ToString(), RequestKey = "", }; var str = JsonUtils.Serialize(msg); byte[] byteMsg = EncodingUtils.GetBytes(str); if (byteMsg == null) { throw new Exception("not parse PartialMessage"); } publishMsg.BytesMsg.Add(byteMsg); } } else { publishMsg.BytesMsg = new List <byte[]>() { EncodingUtils.GetBytes(jsonStr) } }; } } } data.SetMessage(messageEvent); }