Normally, code within a game can only affect the server/clients that the code is running on, but sometimes you’ll need different servers to communicate with each other. This can be accomplished with cross-server messaging offered through
Some examples of
MessagingService usage include:
- Cross-Server Chat — Players can chat with each other even if they’re not in the same server, assuming a maximum of about 20 players.
- Realtime Server Browser — Show a constantly-updating list of servers and who is in them.
- Global Announcements — Let all servers know that a player found a special item in the game.
MessagingService offers two core functions:
MessagingService/SubscribeAsync|SubscribeAsync() subscribes to a developer-defined “topic” and specifies a callback function that detects when messages are published to that topic. For example, a game might subscribe all players to a
"FriendServerEvent" topic which can then receive messages from
MessagingService/PublishAsync|PublishAsync() when any player teleports to a different server.
local MessagingService = game:GetService("MessagingService") local Players = game:GetService("Players") local MESSAGING_TOPIC = "FriendServerEvent" Players.PlayerAdded:Connect(function(player) -- Subscribe to the topic local subscribeSuccess, subscribeConnection = pcall(function() return MessagingService:SubscribeAsync(MESSAGING_TOPIC, function(message) print(message.Data) end) end) if subscribeSuccess then -- Unsubscribe from topic upon player ancestry change player.AncestryChanged:Connect(function() subscribeConnection:Disconnect() end) end end)
- The callback function for
MessagingService/SubscribeAsync|SubscribeAsync()receives a table, not a string. This table contains both
message.Data(the developer-defined data sent via
message.Sentwhich is the Unix time in seconds at which the message was sent.
- As seen on lines 16-18, it's recommended that you call
datatype/RBXScriptConnection|connectionwhen it's no longer necessary to listen for incoming messages to the topic.
MessagingService/PublishAsync|PublishAsync() publishes a message to a specific topic, upon which the callback function for any matching topic will be triggered. For instance, when a player joins a new server,
MessagingService/PublishAsync|PublishAsync() could notify all other players about who just joined that server, along with its
local MessagingService = game:GetService("MessagingService") local Players = game:GetService("Players") local MESSAGING_TOPIC = "FriendServerEvent" Players.PlayerAdded:Connect(function(player) -- Publish to topic local publishSuccess, publishResult = pcall(function() local message = player.Name .. " joined server with 'JobId' of " .. game.JobId MessagingService:PublishAsync(MESSAGING_TOPIC, message) end) if not publishSuccess then print(publishResult) end end)