public void setMessageReceiver() { ConnectionFactory f = new ConnectionFactory() { HostName = "localhost" }; using (IConnection con = f.CreateConnection()) using (IModel channel = con.CreateModel()){ channel.QueueDeclare( queue: Configs.RabbitMQChatKey, exclusive: false, autoDelete: false, arguments: null ); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; string message = Encoding.UTF8.GetString(body); string messageType = "TEXT"; if (message.Contains("file:")) { string keyName = message.Split(":")[1].ToString(); messageType = "FILE"; S3BucketController.S3DownloadObject(keyName, Configs.FileDownloadPath + this.Username); } printChatMessage(this, message, messageType); channel.Close(); }; channel.BasicConsume( queue: Configs.RabbitMQChatKey, autoAck: true, consumer: consumer ); Console.ReadKey(); } }
public async static void SendMessage(this User user, ChatRoom cr, string message) { if (String.IsNullOrEmpty(message)) { Console.WriteLine(space + "No Empty Message Allowed\n\n"); return; } if (cr.HasUser(user.Username)) { ConnectionFactory f = new ConnectionFactory() { HostName = "localhost" }; using (IConnection con = f.CreateConnection()) using (IModel channel = con.CreateModel()){ channel.QueueDeclare( queue: Configs.RabbitMQChatKey, autoDelete: false, exclusive: false, durable: false, arguments: null ); string messageType = "TEXT"; if (message.Contains("file:")) { string[] stringSplitted = message.Split("/"); string keyName = stringSplitted[stringSplitted.Length - 1]; await S3BucketController.S3UploadObject(keyName, message.Split(":")[1]); message = "file:" + keyName; messageType = "FILE"; } var body = Encoding.UTF8.GetBytes(message); PrintChatMessage(user, message); ArrayList onlineChatUserList = Authentication.GetOnlineChatUserList(cr.ConnectedUsers); foreach (ChatUser cu in onlineChatUserList) { if (user.Id.ToString().CompareTo(cu.UserId.ToString()) != 0) { channel.BasicPublish( exchange: "", routingKey: Configs.RabbitMQChatKey, mandatory: true, basicProperties: null, body: body ); cu.setMessageReceiver(); } } channel.Close(); cr.AddChatMessage(user.Id, message, messageType); UpdateChatRoom(cr); } } else { throw (new ChatRoomException("User do not belong to this chat room.")); } }