public void Setup() { MessageData = Encoding.UTF8.GetBytes("hej"); ChannelConfigurator = new ChannelConfigurator(); Exchange = null; MessageProperties = new MessageProperties() { MessageId = MessageId }; _message = new ReceivedMessage(MessageData, GetExchangeName(), MessageProperties); }
public void OnPushNotificationsReceived(ReceivedMessage message) { this.message = "#####PushNotification Received" + "\n"; this.message += "#####Type=" + message.PushMessageType + "\n"; this.message += "#####Sender=" + message.Sender + "\n"; this.message += "#####Scope=" + message.ObjectScope + "\n"; this.message += "#####payload=" + message.GetString ("payload") + "\n"; this.message += "#####msg=" + message.GetString ("msg") + "\n"; }
public void Create_Headers_Equals(string value) { var message = CreateMessage(); var headers = new Dictionary<string, object> {{ value, new UriBuilder()}}; message.Headers.Returns(new ReadOnlyDictionary<string, object>(headers)); var test = new ReceivedMessage<FakeMessage>(message); Assert.Equal(test.Headers, message.Headers); }
// This function will get triggered/executed when a new message is written // on an Azure Service Bus Message Queue called "messages" public static void ProcessQueueMessage([ServiceBusTrigger("messages")] string message, TextWriter log) { Console.WriteLine(message); ReceivedMessage msgModel = new ReceivedMessage(); msgModel.Message = message; using (var deploymentCtx = new DeploymentContext()) { deploymentCtx.ReceivedMessages.Add(msgModel); deploymentCtx.SaveChanges(); } }
/// <summary> /// Get a ReceivedMessage object using the provided parser and message number. /// </summary> /// <param name="parser">IMimeParser object</param> /// <param name="messageNumber">message number</param> /// <returns></returns> public ReceivedMessage GetMessage(IMimeParser parser, int messageNumber) { if (parser == null) { throw new ArgumentNullException("parser"); } TextReader reader = GetMessageReader(messageNumber, false); ReceivedMessage message = parser.Parse(reader); return(message); }
public static int SaveReceivedMessage(ReceivedMessage receivedMessage) { if (HasBeenSaved(receivedMessage)) { UpdateDatabase(receivedMessage); } else { SaveToDatabase(receivedMessage); } return(0); }
public void StoreMessage(ReceivedMessage message) { // Send a message to the chat application var client = new HttpClient(); IList <KeyValuePair <string, string> > formItems = new List <KeyValuePair <string, string> >(); formItems.Add(new KeyValuePair <string, string>("username", message.Username)); formItems.Add(new KeyValuePair <string, string>("message", message.Message)); var content = new FormUrlEncodedContent(formItems); var response = client.PostAsync("http://localhost/message.asp", content).Result; }
public bool HandleAction(User.User user, ReceivedMessage message) { var route = GetCurrentRoute(user); if (route == null) { return(false); } route(user, message); return(true); }
public static bool HasBeenSaved(ReceivedMessage receivedMessage) { try { new ReceivedMessage(receivedMessage.id); return(true); } catch { return(false); } }
// Endless Start reading loop private async void StartReading(Socket client) { var endpoint = client.RemoteEndPoint as IPEndPoint; // Get remote endpoint // Loop theoretically infinetly while (true) { try { long size = await LeadingByteProcessor.ReadLeading(client).ConfigureAwait(false); // leading byte[] bytes = new byte[size]; ArraySegment <byte> segment = new ArraySegment <byte>(bytes); //TODO: Do something when receiving interrupts? Wait for client to come back? // read until all data is read int read = 0; while (read < size) { long receive = size - read; // current buffer size if (receive > ReceiveBufferSize) { receive = ReceiveBufferSize; // max size } ArraySegment <byte> slice = segment.SliceEx(read, (int)receive); // get buffered portion of array read += await client.ReceiveAsync(slice, SocketFlags.None).ConfigureAwait(false); } if (read < 1) { throw new TransferException($"{read} bytes were read! " + "Null bytes could mean a connection shutdown."); } var message = ZeroFormatterSerializer.Deserialize <T>(segment.Array); ReceivedMessage?.Invoke(endpoint, message); // call event } catch (SocketException ex) { Console.WriteLine(ex.ErrorCode); bool success = DisconnectClient(endpoint); // try to disconnect if (success) // Exit Reading loop once successfully disconnected { return; } } catch (TransferException) { // 0 read bytes = null byte bool success = DisconnectClient(endpoint); // try to disconnect if (success) { return; // Exit Reading loop once successfully disconnected } } } // Listen again after client connected }
private static async void botOnMessageReceived(object sender, MessageEventArgs e) { var message = e.Message; if (message == null) { return; } var receivedMessage = new ReceivedMessage() { Text = message.Text, Image = message.Photo, Coordinates = (message.Location == null) ? null : new Coordinates(message.Location), ChatId = message.Chat.Id, Id = message.MessageId, PrivateChat = (message.Chat.Type == ChatType.Private), IsCallback = false, SenderId = message.From.Id, ReplyTo = (message.ReplyToMessage == null) ? (int?)null : message.ReplyToMessage.MessageId, ReplyToText = (message.ReplyToMessage == null) ? (string)null : message.ReplyToMessage.Text, ReplyToBot = (message.ReplyToMessage == null) ? false : (message.ReplyToMessage.From.IsBot && message.ReplyToMessage.From.Id == Bot.BotId), }; receivedMessage.Normalise(); if (message.Photo != null) { if (message.Photo.Length > 0) { var obj = message.Photo.GetValue(message.Photo.Length - 1); if (obj != null && obj is PhotoSize ps) { var imageId = ps.FileId; using var ms = new MemoryStream(); receivedMessage.Image = await Bot.GetInfoAndDownloadFileAsync(imageId, ms); receivedMessage.Image = ms.ToArray(); } } } var result = Processing.ProcessMessage(receivedMessage); if (result == null) { return; } await result.Finish(Bot, receivedMessage); }
internal static async Task Help(ReceivedMessage Message) { var Disabled = new List <string>(); var UserRank = Message.SenderRank(); foreach (var Category in Categories) { if (Category.Key == "" || Message.Feed.FeedInfo.IsEnabled(Category.Key)) { var CategoryCommands = string.Empty; foreach (var Command in Category.Value) { var MinRank = Command.MinRank(Message.Feed.Id); if (UserRank == byte.MaxValue) { CategoryCommands += $"({MinRank}) "; } else if (UserRank < MinRank) { continue; } if (Command.Prefix == CommandType.Command) { CategoryCommands += $"{string.Join(" or ", Command.Keys)} ~ `{Command.Description}`\n"; } else { CategoryCommands += $"{string.Join(" _and_ ", Command.Keys)}\n"; } } if (CategoryCommands != string.Empty) { await Message.Respond($"{(Category.Key == string.Empty ? "**Main**" : "**" + Category.Key + "**")}\n{CategoryCommands}"); await Task.Delay(100); } } else { Disabled.Add($"**{Category.Key}**"); } } if (Disabled.Count > 0) { await Message.Respond($"**Disabled**\n{string.Join(", ", Disabled)}"); } }
private static async Task SearchForObjectByNameAsync(ReceivedMessage receivedMessage, Match regexMatch, SimbadClient simbadClient) { var objectName = regexMatch.Groups["AstroObject"].Value; var foundObject = simbadClient.FindObjectByName(objectName); if (foundObject == null) { WriteObjectNotFound(receivedMessage, objectName); return; } await WriteObjectDetailsEmbeddedAsync(receivedMessage, foundObject).ConfigureAwait(false); }
public void Create_Headers_Equals(string value) { var message = CreateMessage(); var headers = new Dictionary <string, object> { { value, new UriBuilder() } }; message.Headers.Returns(new ReadOnlyDictionary <string, object>(headers)); var test = new ReceivedMessage <FakeMessage>(message, new GetPreviousErrorsNoOp(), NullLoggerFactory.Instance.CreateLogger("null")); Assert.Equal(test.Headers, message.Headers); }
/** * <summary> Update() normal de la classe MonoBehaviour (component). Dans ce cas, s'occupe de traiter la queue des messages. </summary> */ void Update() { while (MessageQueue.Count > 0) { ReceivedMessage msg = MessageQueue.Dequeue(); if (Handlers.ContainsKey(msg.Message.Type) && Handlers[msg.Message.Type] != null) { Handlers[msg.Message.Type](msg.RecInfo, msg.Message); // Exécution des fonctions Handler correspondantes à ce type de message. } } Receiver.Reception(); }
internal static async Task Toggle(ReceivedMessage Message) { var Response = $"category of commands: `{ Message.Text}`"; if (await Message.Feed.FeedInfo.Toggle(Message.Text)) { await Message.Feed.SendAll($"Enabled {Response}"); } else { await Message.Feed.SendAll($"Disabled {Response}"); } }
public void Read_contact_information() { ReceivedMessage <Contact> receivedMessage = (ReceivedMessage <Contact>)ReceivedMessage.Parse(Utils.ReadFile(JsonsDirectory + "file\\contactreceived.json")); Contact expectedContact = new Contact() { Name = "Ehsan Sabet", Phone = "+989356167766" }; receivedMessage.Data.Should().BeEquivalentTo(expectedContact); }
/// <summary> /// Given a received message (returned from a pull request from a subscription) /// and a subscription, construct a PubSub message with AckId and subscription. /// </summary> public PubSubMessageWithAckIdAndSubscription(ReceivedMessage receivedMessage, string subscription) { Subscription = subscription; AckId = receivedMessage.AckId; if (receivedMessage.Message != null) { Attributes = receivedMessage.Message.Attributes; Data = receivedMessage.Message.Data; ETag = receivedMessage.Message.ETag; MessageId = receivedMessage.Message.MessageId; PublishTime = receivedMessage.Message.PublishTime; } }
public void OnPushNotificationsReceived(ReceivedMessage message) { this.message = "#####PushNotification Received" + "\n"; this.message += "#####Type=" + message.PushMessageType + "\n"; this.message += "#####Sender=" + message.Sender + "\n"; this.message += "#####Scope=" + message.ObjectScope + "\n"; this.message += "#####msg=" + message.GetString ("msg") + "\n"; PushToAppMessage msg = (PushToAppMessage)message; msg.KiiObject.Refresh ((KiiObject obj, Exception e) => { this.message += "#####payload=" + obj.GetString ("payload"); }); }
internal async static Task Choose(ReceivedMessage Message) { if (Message.Text.StartsWith("between")) { Message.Text = Message.Text.Substring("between").TrimStart(); } if (Message.Text != string.Empty) { var Split = Message.Text.Replace(" and ", ",").Split(','); Message.Respond("I choose " + Split[new Random().Next(0, Split.Length)].Trim()); } }
public MessageManager(List <SentMessage> queue, string[][] buttons, bool preferToUpdate, Queue <SentMessage> lastMessages, ChatId chatId, ReceivedMessage recievedMessage, ShownStats shownStats, string intent) { Queue = queue; Buttons = buttons ?? new string[0][]; PreferToUpdate = preferToUpdate; ReceivedMessage = recievedMessage; LastMessages = lastMessages; ChatId = chatId; ShownStats = shownStats; _intent = intent; LastMessage = LastMessages.LastOrDefault(); }
public async Task ThenTransformFailsWithInvalidUserMessageWithSoapAS4StreamAsync() { // Arrange AS4Message as4Message = CreateAS4MessageWithoutAttachments(); as4Message.AddMessageUnit(new UserMessage("message-id")); MemoryStream memoryStream = as4Message.ToStream(); var receivedMessage = new ReceivedMessage(memoryStream, Constants.ContentTypes.Mime); // Act / Assert await Assert.ThrowsAnyAsync <Exception>(() => Transform(receivedMessage)); }
public void Create_Headers_Equals(string value) { var message = CreateMessage(); var headers = new Dictionary <string, object> { { value, new UriBuilder() } }; message.Headers.Returns(new ReadOnlyDictionary <string, object>(headers)); var test = new ReceivedMessage <FakeMessage>(message); Assert.Equal(test.Headers, message.Headers); }
internal static async Task Remove(ReceivedMessage Message) { var SongNames = await Message.Feed.Music.RemoveSongs(Message.Text.ParseInts()); if (SongNames.Length > 0) { await Message.Respond($"**Removed**\n{string.Join("\n", SongNames.Select(x => $"`{x}`"))}"); } else { await Message.Respond($"No songs were removed"); } }
void OnConnect(ReceivedMessage message) { _logger.LogInfo("client request to connect from " + message.Result.RemoteEndPoint); var netId = new Guid(message.Message.Data.ToString()); var gameClient = new GameClient(netId, message.Result.RemoteEndPoint); _connectedClients.AddOrUpdateByGuid(netId, gameClient); _udpServer.MessageSender.SendConnected(gameClient); _udpServer.MessageSender.SendNewPlayerToOtherClients(gameClient); _logger.LogInfo("Client connected: " + gameClient.Id); }
public override void OnMessage(User user, ReceivedMessage message) { if (message.Text == "А когда HL-3 выйдет?") { SendMessage(user, "За толстыми линзами очков блеснули слезы. Гик пошатнулся, рухнул на пол, свернулся калачиком и тихонько заплакал. Вокруг него образовалась небольшая лужа. Думаю, нам пора оставить его наедине с собой на некоторое время"); user.RoomManager.Leave(); } else { base.OnMessage(user, message); } }
private async Task ProcessSingleMessageAsync(ReceivedMessage message) { try { await ProcessAsync(message?.Message?.Data?.ToStringUtf8()); await _messagingService.AckMessageAsync(SubscriptionName, message.AckId); } catch (Exception e) { _logger.Error(e.Message, e); } }
public new void OnMessage(User user, ReceivedMessage message) { var variables = Room.GetRoomVariables(user); var itemToUse = user.ItemManager.Items.SingleOrDefault(i => i.CanUse(user) && message.Text.StartsWith(i.Item.Name) ); if (itemToUse == null) { Room.SendMessage(user, "Нельзя такое использовать", Room.GetActions(user)); return; } using (var ctx = new UserContext((UserId)variables.Get("enemy"))) { var enemyVariables = Room.GetRoomVariables(ctx); if (variables.Get <Serializable.Bool>("turn") != true) { var lastMessage = DateTimeOffset.FromUnixTimeSeconds(enemyVariables.Get <Serializable.Long>("lastMessage")); if (DateTimeOffset.Now - lastMessage > TimeSpan.FromMinutes(1.5)) { enemyVariables.Set("lastMessage", new Serializable.Long(DateTimeOffset.Now.ToUnixTimeSeconds())); Room.SendMessage(user, "Пока противник спит, вы наносите ещё один удар!", Room.GetActions(user)); } else { Room.SendMessage(user, "Не ваш ход, увы", Room.GetActions(user)); return; } } enemyVariables.Set("turn", new Serializable.Bool(true)); variables.Set("turn", new Serializable.Bool(false)); variables.Set("lastMessage", new Serializable.Long(DateTimeOffset.Now.ToUnixTimeSeconds())); } // Must be outside of ctx (up to 3 user deserialization!) itemToUse.OnUse(user); using (var ctx = new UserContext((UserId)variables.Get("enemy"))) { Room.SendMessage(ctx, "Ваш ход! Чем же вы ответите?"); // Force send message to damaged user ctx.User.MessageManager.Finish(); } }
private static async Task SearchForObjectsAroundRaDecAsync(ReceivedMessage receivedMessage, Match regexMatch, SimbadClient simbadClient) { RaDecCoordinate centerCoordinates = null; const float radiusInDegrees = 0.5f; try { if (regexMatch.Groups["CenterOfSearchRA"].Success) { centerCoordinates = new RaDecCoordinate( double.Parse(regexMatch.Groups["CenterOfSearchRA"].Value, CultureInfo.InvariantCulture), double.Parse(regexMatch.Groups["CenterOfSearchDEC"].Value, CultureInfo.InvariantCulture)); } else if (regexMatch.Groups["CenterOfSearchName"].Success) { var name = regexMatch.Groups["CenterOfSearchName"].Value; var queryAroundObject = simbadClient.FindObjectByName(name); if (queryAroundObject == null) { await receivedMessage.Channel.SendMessageAsync($"No object with name {name} found in the SIMBAD databse!").ConfigureAwait(false); return; } centerCoordinates = queryAroundObject.RaDecCoordinate; } } finally { if (centerCoordinates == null) { await receivedMessage.Channel.SendMessageAsync("Could not parse RA/DEC coordinates").ConfigureAwait(false); } } var objectsAroundTarget = simbadClient.QueryAround(centerCoordinates, radiusInDegrees); var csvString = CsvExporter.AstronomicalObjectsToCsv(objectsAroundTarget); await receivedMessage.Channel.SendMessageAsync($"Found {objectsAroundTarget.Count} objects around {centerCoordinates} within a radius of {radiusInDegrees}°:").ConfigureAwait(false); await receivedMessage.Channel.SendMessageAsync( new SendMessage( content : null, new List <Attachment> { new SendAttachment { Name = "queryResult.csv", Content = Encoding.ASCII.GetBytes(csvString) } })).ConfigureAwait(false); }
public static bool UpdateDatabase(ReceivedMessage receivedMessage) { string sqlStr = " update wxreceivemsg set " + " wxreceivemsg_to = '" + receivedMessage.to.Trim().Replace("'", "") + "' , " + " wxreceivemsg_from = '" + receivedMessage.from.Trim().Replace("'", "") + "' , " + " wxreceivemsg_time = '" + receivedMessage.time.ToString().Trim().Replace("'", "") + "' , " + " wxreceivemsg_type = '" + receivedMessage.type.Trim().Replace("'", "") + "' , " + " wxreceivemsg_picurl = '" + receivedMessage.picUrl.Trim().Replace("'", "") + "' , " + " wxreceivemsg_mediaid = '" + receivedMessage.mediaId.Trim().Replace("'", "") + "' , " + " wxreceivemsg_format = '" + receivedMessage.format.Trim().Replace("'", "") + "' , " + " wxreceivemsg_thumbmediaid = '" + receivedMessage.thumbMediaId.Trim().Replace("'", "") + "' , " + " wxreceivemsg_locationx = '" + receivedMessage.lat.Trim().Replace("'", "") + "' , " + " wxreceivemsg_locationy = '" + receivedMessage.lon.Trim().Replace("'", "") + "' , " + " wxreceivemsg_scale = '" + receivedMessage.scale.Trim().Replace("'", "") + "' , " + " wxreceivemsg_label = '" + receivedMessage.label.Trim().Replace("'", "") + "' , " + " wxreceivemsg_title = '" + receivedMessage.title.Trim().Replace("'", "") + "' , " + " wxreceivemsg_description = '" + receivedMessage.description.Trim().Replace("'", "") + "' , " + " wxreceivemsg_url = '" + receivedMessage.url.Trim().Replace("'", "") + "' , " + " wxreceivemsg_content = '" + receivedMessage.content.Trim().Replace("'", "") + "' , " + " wxreceivemsg_event = '" + receivedMessage.userEvent.Trim().Replace("'", "") + "' , " + " wxreceivemsg_eventkey = '" + receivedMessage.eventKey.Trim().Replace("'", "") + "' , " + " wxreceivemsg_recognition = '" + receivedMessage.recognition.Trim().Replace("'", "") + "' , " + " wxreceivemsg_isreply = '" + (receivedMessage.hasReplied ? "1" : "0") + "' , " + " wxreceivemsg_deal = '" + (receivedMessage.hasDealed ? "1" : "0") + "' , " + " wxreceivemsg_upd = dbo.GetLocalDate(DEFAULT) " + " where wxreceivemsg_id = '" + receivedMessage.id.Trim().Replace("'", "") + "' "; SqlConnection conn = new SqlConnection(Util.conStr.Trim()); SqlCommand cmd = new SqlCommand(sqlStr, conn); conn.Open(); int i = 0; try { i = cmd.ExecuteNonQuery(); } catch { } conn.Close(); cmd.Dispose(); conn.Dispose(); if (i == 0) { return(false); } else { return(true); } }
public static Tuple <INetworkChannel, INetworkChannel> GetConnectedChannels() { var channel1 = new Mock <INetworkChannel>(); var channel2 = new Mock <INetworkChannel>(); Action <ReceivedMessage> channel1ReceiveFunction = null; Action <ReceivedMessage> channel2ReceiveFunction = null; var channel1Client = new Client("10.0.0.1", 123); var channel2Client = new Client("10.0.0.2", 321); Action <Client> channel1OnClient = null; Action <Client> channel2OnClient = null; channel1.Setup(c => c.Send(It.IsAny <Client>(), It.IsAny <string>())).Callback <Client, string>((c, p) => { ReceivedMessage message = new ReceivedMessage(channel1Client, p); channel2ReceiveFunction.Invoke(message); }); channel1.Setup(c => c.OnReceive(It.IsAny <Action <ReceivedMessage> >())).Callback <Action <ReceivedMessage> >( function => channel1ReceiveFunction = function ); channel2.Setup(c => c.Send(It.IsAny <Client>(), It.IsAny <string>())).Callback <Client, string>((c, p) => { ReceivedMessage message = new ReceivedMessage(channel2Client, p); channel1ReceiveFunction.Invoke(message); }); channel2.Setup(c => c.OnReceive(It.IsAny <Action <ReceivedMessage> >())).Callback <Action <ReceivedMessage> >( function => channel2ReceiveFunction = function ); channel2.Setup(c => c.OnClientConnect(It.IsAny <Action <Client> >())).Callback <Action <Client> >(a => { channel2OnClient = a; channel2OnClient.Invoke(channel1Client); }); channel1.Setup(c => c.OnClientConnect(It.IsAny <Action <Client> >())).Callback <Action <Client> >(a => { channel1OnClient = a; channel1OnClient.Invoke(channel2Client); }); Tuple <INetworkChannel, INetworkChannel> channels = new Tuple <INetworkChannel, INetworkChannel>(channel1.Object, channel2.Object); return(channels); }
public void StoreReceivedMessage(ReceivedMessage message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } using (var scope = CreateScope()) { var dbContext = (DbContext)scope.ServiceProvider.GetRequiredService(Options.DbContextType); dbContext.Entry(message).Property("Version").CurrentValue = Options.Version; dbContext.Set <ReceivedMessage>().Add(message); dbContext.SaveChanges(); } }
public override string ProcessMessage(ReceivedMessage msg) { string result = string.Empty; if (msg.Text.IndexOf("!", 0, 1) >= 0) { string cmd = msg.Text.Remove(0, 1).ToLower(); if (cmd.StartsWith("xyu ")) { result = ReturnRandomXyu(cmd.Remove(0, 4)); } } return(result); }
private static Task PrintServerConfigAsync(ReceivedMessage receivedMessage) { var configStore = receivedMessage.ApiWrapper.ConfigStore; var configEntries = configStore.GetAllConfigValues(receivedMessage.Channel.ParentServer).OrderBy(x => x.Key); var configTable = ""; foreach (var configEntry in configEntries) { configTable += $"{(configEntry.Key + ":").PadRight(30)}{configEntry.Value}\r\n"; } return(receivedMessage.Channel.SendMessageAsync($"Current config for this server:" + $"\r\n{receivedMessage.ApiWrapper.MessageFormatter.CodeBlock(configTable, "json")}")); }
public void GetHeader(string value) { var fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); var message = CreateMessage(); var test = new ReceivedMessage<FakeMessage>(message); var messageContextDataFactory = fixture.Create<IMessageContextDataFactory>(); var headerData = new HeaderData(); messageContextDataFactory.Create(value, headerData) .Returns(new MessageContextData<HeaderData>(value, headerData)); var property = messageContextDataFactory.Create(value, headerData); Assert.Equal(test.GetHeader(property), headerData); }
public void ReceiveMessage(ReceivedMessage message) { _receivedMessages.Add(message); while (_receivedMessages.Count > MaxMessageHistory) { _receivedMessages.RemoveAt(0); } NotifyOfPropertyChange(() => ChatHistory); }
public bool IsPartitionConsumingComplete(ReceivedMessage currentMessage) { return _stoppingOffsets.IsPartitionConsumingComplete(currentMessage); }
public bool IsPartitionConsumingComplete(ReceivedMessage currentMessage) { return false; }
public void ParseMessage() { #region Handle Errors if (p_state>=100) { LastErrorMessage+= "GameNetwork.ParseMessage: Unhandled Error state code= "+p_state.ToString(); IsError=true; return; };//необработанная ошибка if (p_Data == null || p_Data.Length <= 0) { p_state=110; LastErrorMessage+="GameNetwork.ParseMessage: Data is Null or empty"; return;} if (pd_length <= 0) { p_state = 111; LastErrorMessage += "GameNetwork.ParseMessage: Read length <= 0"; return; } if (pd_length >= p_Data.Length) { p_state = 112; LastErrorMessage += "GameNetwork.ParseMessage: Data.length<=Read Length"; return; } if (pd_index >= p_Data.Length) { p_state = 113; LastErrorMessage += "GameNetwork.ParseMessage: Index>Data.Length"; return; } #endregion #region State 0 - Read New Message if (p_state == 0) { p_currentMsg=new ReceivedMessage(); //read ID #region Need more bytes for Length if (pd_index+4>pd_length) { p_state=1; pd_needbytes = pd_index + 4 - pd_length; if (pd_needbytes==1)//have 3 { /*p_tmp[0]=p_Data[pd_index+3];*/p_tmp[1]=p_Data[pd_index+2]; p_tmp[2]=p_Data[pd_index+1];p_tmp[3]=p_Data[pd_index ]; pd_index+=3; } else if (pd_needbytes==2)//have 2 { /*p_tmp[0]=p_Data[pd_index+3];p_tmp[1]=p_Data[pd_index+2];*/ p_tmp[2]=p_Data[pd_index+1];p_tmp[3]=p_Data[pd_index ]; pd_index+=2; } else if (pd_needbytes==3)//have 1 { /*p_tmp[0]=p_Data[pd_index+3];p_tmp[1]=p_Data[pd_index+2]; p_tmp[2]=p_Data[pd_index+1];*/p_tmp[3]=p_Data[pd_index ]; pd_index+=1; } else { //nothinc p_currentMsg = null; Log.LogError("GameNetwork.ParseMessage: Невозможная ситуация, Блядь!"); } return; } #endregion p_tmp[0]=p_Data[pd_index+3];p_tmp[1]=p_Data[pd_index+2]; p_tmp[2]=p_Data[pd_index+1];p_tmp[3]=p_Data[pd_index ]; pd_index+=4; p_itmp=BitConverter.ToInt32(p_tmp,0); if (p_itmp > 0) { //Create New Message p_currentMsg.IsReaded=false; p_currentMsg.LifeTime=MaxReciveLifeTime; p_currentMsg.RawData=new byte [p_itmp]; if (pd_index+p_itmp>pd_length) { // Not enough data, need read more data Array.Copy(p_Data, pd_index, p_currentMsg.RawData, 0, pd_length - pd_index); pd_needbytes = p_itmp - pd_index - pd_length; pd_readedIndex = pd_length - pd_index; p_state = 3; } else { //Enough data - complete message. Array.Copy(p_Data,pd_index,p_currentMsg.RawData,0,p_itmp); pd_index+=p_itmp; p_state=0; return; } } else { //error p_state = 115; LastErrorMessage += "GameNetwork.ParseMessage: Message length <=0"; return; } } else #endregion #region State 1 - Continue read ID if (p_state==1) { #region Parse `end of Length` or continue read. switch (pd_needbytes) { case 1: if (pd_index + 1 > pd_length) { /* //Need more bytes p_state = 1; pd_needbytes = 1; return; */ Log.LogError("GameNetwork.ParseMessage: Т.е. было прочитано 0 байт. Блядь!"); } else { p_tmp[0]=p_Data[pd_index]; /*p_tmp[1] = p_Data[pd_index + 2]; p_tmp[2] = p_Data[pd_index + 1]; p_tmp[3] = p_Data[pd_index];*/ pd_index += 1; } break; case 2: if (pd_index + 2 > pd_length) { //Need more bytes p_state = 1; pd_needbytes = pd_index + 2 - pd_length; if (pd_needbytes == 1)//have 3 { /*p_tmp[0]=p_Data[pd_index+3];*/p_tmp[1] = p_Data[pd_index]; //p_tmp[2] = p_Data[pd_index + 1]; p_tmp[3] = p_Data[pd_index]; pd_index += 1; } else Log.LogError("GameNetwork.ParseMessage: Т.е. было прочитано 0 байт. Блядь!"); return; } else { p_tmp[1] = p_Data[pd_index]; p_tmp[0] = p_Data[pd_index+1]; pd_index += 2; } break; case 3: if (pd_index + 3 > pd_length) { //Need more bytes p_state = 1; pd_needbytes = pd_index + 3 - pd_length; if (pd_needbytes == 1)//have 3 { p_tmp[1] = p_Data[pd_index]; p_tmp[0] = p_Data[pd_index+1]; pd_index += 2; } else if (pd_needbytes == 2) { p_tmp[1] = p_Data[pd_index]; pd_index += 1; } else Log.LogError("GameNetwork.ParseMessage: Т.е. было прочитано 0 байт. Блядь!"); return; } else { p_tmp[2] = p_Data[pd_index]; p_tmp[1] = p_Data[pd_index+1]; p_tmp[0] = p_Data[pd_index + 2]; pd_index += 3; } break; default: p_state = 113; return; } #endregion p_itmp = BitConverter.ToInt32(p_tmp, 0); if (p_itmp > 0) { //Create New Message p_currentMsg.IsReaded = false; p_currentMsg.LifeTime = MaxReciveLifeTime; p_currentMsg.RawData = new byte[p_itmp]; if (pd_index + p_itmp > pd_length) { // Not enough data, need read more data Array.Copy(p_Data, pd_index, p_currentMsg.RawData, 0, pd_length - pd_index); pd_needbytes = p_itmp - pd_index - pd_length; pd_readedIndex = pd_length - pd_index; p_state = 3; } else { //Enough data - complete message. Array.Copy(p_Data, pd_index, p_currentMsg.RawData, 0, p_itmp); pd_index += p_itmp; p_state = 0; return; } } else { p_state = 115; LastErrorMessage += "GameNetwork.ParseMessage: Message length <=0"; return; } } else #endregion #region State 3 - Continue read Data if (p_state == 3) { if (pd_index + pd_needbytes > pd_length) { Array.Copy(p_Data, pd_index, p_currentMsg.RawData, pd_readedIndex, pd_length - pd_index); pd_readedIndex += pd_length - pd_index; pd_needbytes = pd_needbytes - pd_index - pd_length; p_state = 3; } else { Array.Copy(p_Data, pd_index, p_currentMsg.RawData, pd_readedIndex, pd_needbytes); pd_index += pd_needbytes; p_state = 0; return; } } else #endregion #region Wrong State { p_state = 116; LastErrorMessage += "GameNetwork.ParseMessage:Wrong State ="+p_state.ToString(); return; } #endregion }
// Callback method from the UDPClient. // This is called when the asynchronous receive procedure received a message private void EndAsyncReceive(IAsyncResult objResult) { // Create an empty EndPoint, that will be filled by the UDPClient, holding information about the sender IPEndPoint objSendersIPEndPoint = new IPEndPoint(IPAddress.Any, 0); // Read the message byte[] objByteMessage = objUDPClient.EndReceive(objResult, ref objSendersIPEndPoint); // If the received message has content and it was not sent by ourselves... if (objByteMessage.Length > 0 && !objSendersIPEndPoint.Address.ToString().Equals(myIPAddress)) { // Translate message to string string strReceivedMessage = System.Text.Encoding.ASCII.GetString(objByteMessage); // Create a ReceivedMessage struct to store this message in the list ReceivedMessage objReceivedMessage = new ReceivedMessage(); objReceivedMessage.fTime = lastUpdateTime; objReceivedMessage.strIP = objSendersIPEndPoint.Address.ToString(); objReceivedMessage.bIsReady = strReceivedMessage == strServerReady ? true : false; lstReceivedMessages.Add(objReceivedMessage); } // Check if we're still searching and if so, restart the receive procedure if (currentState == enuState.Searching) BeginAsyncReceive(); }
public void AddSkipped(ReceivedMessage message) { _skipped.Add(message); }
public void AddReceived(ReceivedMessage message) { _received.Add(message); _skipped.Remove(message); }
public void Create_Body_Equals() { var message = CreateMessage(); var test = new ReceivedMessage<FakeMessage>(message); Assert.Equal(test.Body, message.Body); }
public void Create_CorrelationId_Equals() { var message = CreateMessage(); var test = new ReceivedMessage<FakeMessage>(message); Assert.Equal(test.CorrelationId, message.CorrelationId); }
public override void Receive(ReceivedMessage message) { base.Receive(message); throw new InvalidOperationException("an exception"); }
private void Poll() { if (shuttingDown) { return; } byte[] readBuffer = new byte[tcpClient.ReceiveBufferSize]; // These are for the current message string subject = null; int subscriptionID = 0; int needed = 0; string inboxID = null; StringBuilder messageBuffer = null; while (false == shuttingDown) { if (NatsMessagingStatus.RUNNING != status && NatsMessagingStatus.CONNECTING != status) { // Shutting down break; } ReceiveMoreData: bool interrupted = false, disconnected = false; if (null == messageBuffer) { messageBuffer = new StringBuilder(); } try { do { int bytesRead = tcpClient.Read(readBuffer); messageBuffer.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead)); } while (tcpClient.DataAvailable()); } catch (InvalidOperationException ex) { log.Error(ex, Resources.NatsMessagingProvider_DisconnectedInPoll_Message); disconnected = true; } catch (IOException ex) { interrupted = HandleException(ex, SocketError.Interrupted); disconnected = false == interrupted; } if (disconnected && false == shuttingDown) { if (false == Reconnect()) { log.Fatal(Resources.NatsMessagingProvider_CouldNotReconnect_Message); status = NatsMessagingStatus.ERROR; break; } } if (interrupted && shuttingDown) { // Blocking call was canceled break; } if (messageBuffer.Length > 0) { while (null != messageBuffer) { string incomingData = messageBuffer.ToString(); log.Trace("Parsing: '{0}'", incomingData); switch (currentParseState) { case ParseState.AWAITING_CONTROL_LINE: { if (MSG.IsMatch(incomingData)) { Match match = MSG.Match(incomingData); incomingData = match.Postmatch(incomingData); GroupCollection groups = match.Groups; if (groups.Count > 0) { subject = groups[1].Value; subscriptionID = Convert.ToInt32(groups[2].Value, CultureInfo.InvariantCulture); inboxID = groups[4].Value; needed = Convert.ToInt32(groups[5].Value, CultureInfo.InvariantCulture); currentParseState = ParseState.AWAITING_MSG_PAYLOAD; } } else if (OK.IsMatch(incomingData)) { Match match = OK.Match(incomingData); incomingData = match.Postmatch(incomingData); } else if (ERR.IsMatch(incomingData)) { Match match = ERR.Match(incomingData); incomingData = match.Postmatch(incomingData); GroupCollection groups = match.Groups; if (groups.Count > 0) { string errorData = match.Groups[1].Value; log.Info(Resources.NatsMessagingProvider_NatsErrorReceived_Fmt, errorData); } } else if (PING.IsMatch(incomingData)) { Write(PongResponse); Match match = PING.Match(incomingData); incomingData = match.Postmatch(incomingData); } else if (PONG.IsMatch(incomingData)) { // TODO: callbacks? Match match = PONG.Match(incomingData); incomingData = match.Postmatch(incomingData); } else if (INFO.IsMatch(incomingData)) { Match match = INFO.Match(incomingData); incomingData = match.Postmatch(incomingData); GroupCollection groups = match.Groups; if (groups.Count > 0) { string infoData = groups[1].Value; log.Info(Resources.NatsMessagingProvider_NatsInfoReceived_Fmt, infoData); } } else if (UNKNOWN.IsMatch(incomingData)) { Match match = UNKNOWN.Match(incomingData); incomingData = match.Postmatch(incomingData); log.Error(Resources.NatsMessagingProvider_NatsUnknownReceived_Fmt, match.Value); } else { // If we are here we do not have a complete line yet that we understand. goto ReceiveMoreData; } messageBuffer.Clear(); messageBuffer.Append(incomingData); if (0 == messageBuffer.Length) { messageBuffer = null; } } break; case ParseState.AWAITING_MSG_PAYLOAD: { if (messageBuffer.Length < (needed + CRLFLen)) { goto ReceiveMoreData; } else { string message = messageBuffer.ToString(0, needed); var receivedMessage = new ReceivedMessage(subject, subscriptionID, inboxID, message); lock (messageQueue) { messageQueue.Enqueue(receivedMessage); messageQueuedEvent.Set(); } int startIndex = needed + CRLFLen; int length = messageBuffer.Length - startIndex; string remaining = messageBuffer.ToString(startIndex, length); if (remaining.Length > 0) { messageBuffer = new StringBuilder(remaining); } else { messageBuffer = null; } // NB: do resets last inboxID = String.Empty; subscriptionID = 0; needed = 0; currentParseState = ParseState.AWAITING_CONTROL_LINE; } } break; } } } } messageQueuedEvent.Set(); }
public bool IsPartitionConsumingComplete(ReceivedMessage currentMessage) { // "NextOffset" is the "Next" offset, so subtract one to get the current offset. var stopOffset = NextOffset(currentMessage.Partition) - 1; return currentMessage.Offset == stopOffset; }
void Update() { if (_objResult != null) { // Create an empty EndPoint, that will be filled by the UDPClient, holding information about the sender IPEndPoint objSendersIPEndPoint = new IPEndPoint(IPAddress.Any, 0); // Read the message byte[] objByteMessage = objUDPClient.EndReceive(_objResult, ref objSendersIPEndPoint); // If the received message has content and it was not sent by ourselves... if (objByteMessage.Length > 0 && !objSendersIPEndPoint.Address.ToString().Equals(Network.player.ipAddress)) { // Translate message to string string strReceivedMessage = System.Text.Encoding.ASCII.GetString(objByteMessage); // Create a ReceivedMessage struct to store this message in the list ReceivedMessage objReceivedMessage = new ReceivedMessage(); objReceivedMessage.fTime = Time.time; objReceivedMessage.strIP = objSendersIPEndPoint.Address.ToString(); objReceivedMessage.bIsReady = strReceivedMessage == strServerReady ? true : false; lstReceivedMessages.Add(objReceivedMessage); } // Check if we're still searching and if so, restart the receive procedure if (currentState == enuState.Searching) BeginAsyncReceive(); _objResult = null; } // Check if we need to send messages and the interval has espired if ((currentState == enuState.Searching || currentState == enuState.Announcing) && Time.time > fTimeLastMessageSent + fIntervalMessageSending) { // Determine out of our current state what the content of the message will be byte[] objByteMessageToSend = System.Text.Encoding.ASCII.GetBytes(currentState == enuState.Announcing ? strServerReady : strServerNotReady); // Send out the message objUDPClient.Send(objByteMessageToSend, objByteMessageToSend.Length, new IPEndPoint(IPAddress.Broadcast, 22043)); // Restart the timer fTimeLastMessageSent = Time.time; // Refresh the list of received messages (remove old messages) if (currentState == enuState.Searching) { // This rather complex piece of code is needed to be able to loop through a list while deleting members of that same list bool bLoopedAll = false; while (!bLoopedAll && lstReceivedMessages.Count > 0) { foreach (ReceivedMessage objMessage in lstReceivedMessages) { if (Time.time > objMessage.fTime + fTimeMessagesLive) { // If this message is too old, delete it and restart the foreach loop lstReceivedMessages.Remove(objMessage); break; } // If this whas the last message, make sure we exit the while loop if (lstReceivedMessages[lstReceivedMessages.Count - 1].Equals(objMessage)) bLoopedAll = true; } } } } if (currentState == enuState.Searching) { // Check the list of messages to see if there is any 'i have a server ready' message present foreach (ReceivedMessage objMessage in lstReceivedMessages) { // If we have a server that is ready, call the right delegate and stop searching if (objMessage.bIsReady) { StopSearching(); strMessage = "We will join"; delWhenServerFound(objMessage.strIP); break; } } // Check if we're ready searching. if (currentState == enuState.Searching && Time.time > fTimeSearchStarted + fTimeToSearch) { // We are. Now determine who's gonna be the server. // This string holds the ip of the new server. We will start off pointing ourselves as the new server string strIPOfServer = Network.player.ipAddress; // Next, we loop through the other messages, to see if there are other players that have more right to be the server (based on IP) foreach (ReceivedMessage objMessage in lstReceivedMessages) { if (ScoreOfIP(objMessage.strIP) > ScoreOfIP(strIPOfServer)) { // The score of this received message is higher, so this will be our new server strIPOfServer = objMessage.strIP; } } // If after the loop the highest IP is still our own, call delegate to start a server and stop searching if (strIPOfServer == Network.player.ipAddress) { StopSearching(); strMessage = "We will start server."; delWhenServerMustStarted(); } // If it's not, someone else must start the server. We will simply have to wait as the server is clearly not ready yet else { strMessage = "Found server. Waiting for server to get ready..."; // Clear the list and do the search again. lstReceivedMessages.Clear(); fTimeSearchStarted = Time.time; } } } }
public void Receive(ReceivedMessage message) { _action.Invoke(message); }
public virtual void Receive(ReceivedMessage message) { Message = message; if (_listener != null) { _listener.Stop(); } }
void DoStartAndReadMessages() { if (client == null) { LastErrorMessage = LastErrorMessage + "Client.Connect: Client is Null\n"; IsError = true; return; } if (!client.Connected) { try { client.Connect(RemotePoint); IsConnected = true; } catch (System.Exception ex) { LastErrorMessage += ex.Message; IsError = true; } } if (!client.Connected) return; //Подключились //Начинаем писать if (NeedStartWrite) { try { NeedStartWrite = false; WriteThread.Start(); } catch (Exception ex) { IsError = true; LastErrorMessage += "GameNetwork at TryStartWriteThread: " + ex.Message; } } //начинаем читать while (!NeedStopRead) { if (IsError) { Thread.Sleep(WasErrorSleepTime); continue; } if (!client.Connected) { IsError = true; LastErrorMessage = "GameNetwork.Read: connection breaks?"; continue; } try { pd_oldLength = pd_length; pd_length = client.GetStream().Read(ReadBuffer, 0, ReadBuffer.Length); p_Data = ReadBuffer; pd_index = 0; } catch (Exception ex) { IsError = true; LastErrorMessage += ex.Message; } if (!client.Connected || pd_length==0) { IsError = true; LastErrorMessage = "GameNetwork.Read: connection breaks?"; continue; } if (pd_length == 0) { IsError = true; LastErrorMessage = "GameNetwork.Read: Was read 0 bytes - maybe connection breaks?"; continue; } if (IsError) continue; //Read message ParseMessage(); if (p_state==0) { //Parse binary_to_term string err=""; p_currentMsg.Data = Term.binary_to_term(ref p_currentMsg.RawData, ref err); if (p_currentMsg.Data == null) { IsError = true; LastErrorMessage += "GameNetwork.ReadMessage: BinToTerm Error: " + err; } else { //Finde Recive Handler err=p_currentMsg.SetHandler(); if (err!=null) { IsError = true; LastErrorMessage += "GameNetwork.ReadMessage: Set Message Handler Error: "+err; } else { // Add Message To Update; lock (ReadLocker) { ReadMessages.AddLast(p_currentMsg); } p_currentMsg = null; } } } else if (p_state >= 100) { IsError = true; LastErrorMessage += "GameNetwork.ReadMessage: ParseError, code=" + p_state.ToString(); } //else ... continue read message. } }
private IRpcQueue<object, MessageExpression> CreateRpc(IFixture fixture) { fixture.Inject(new MessageProcessingRpcReceiveTests().Create()); var receive = fixture.Create<IMessageProcessingRpcSend<MessageExpression>>(); receive .Handle(null, null, TimeSpan.MaxValue) .ReturnsForAnyArgs(new SentMessage(new RpcQueueTests.MessageId(), new RpcQueueTests.CorrelationId())); receive .Handle(null, TimeSpan.MaxValue) .ReturnsForAnyArgs(new SentMessage(new RpcQueueTests.MessageId(), new RpcQueueTests.CorrelationId())); fixture.Inject(receive); var message = fixture.Create<IMessage>(); fixture.Inject(message); var newMessage = new ReceivedMessage<object>(new ReceivedMessageInternal(message, new RpcQueueTests.MessageId(), new RpcQueueTests.CorrelationId())); var handler = fixture.Create<IMessageHandlerRegistration>(); handler.GenerateMessage(null).ReturnsForAnyArgs(newMessage); fixture.Inject(handler); return new RpcQueue<object, MessageExpression>(fixture.Create<QueueRpcConfiguration>(), fixture.Create<QueueConsumerConfiguration>(), fixture.Create<IClearExpiredMessagesRpcMonitor>(), fixture.Create<ILogFactory>(), fixture.Create<MessageProcessingRpcReceive<object>>(), receive, fixture.Create<IQueueWaitFactory>()); }