Socket Module
Disclaimer: Roblox does not natively support sockets. This module provides a socket-like interface built on top of Roblox’s RemoteEvents for client-server communication.
Github Repo | Download Socket.rbxm
The “Socket” module provides a simple, event-based interface for client-server communication
in Roblox, similar to socket.io. It wraps around RemoteEvents and offers the following key features:
-
Event Listening: Register event listeners using
On, remove them withOff, or listen only once withOnce. -
Event Emission: Use
Emitto send events to all clients (from the server) or to the server (from the client). UseEmitTofor targeted messaging (server only). -
Remote Procedure Calls: The
Callmethod allows a client to call a server function and wait for a response within a timeout. -
Broadcasting:
BroadcastExceptlets the server send an event to all players except one. -
Latency measurement: The
Pingmethod helps measure client-to-server latency.
Features and Usage Examples
1. Event Listening
Register event callbacks on both sides using On.
Example (client-side):
socket:On("HelloFromServer", function(message)
print("Client received:", message)
end)
On the server side:
socket:On("HelloFromClient", function(player, message)
print("Server received from", player.Name, ":", message)
end)
2. Emitting Events
Use Emit to send events.
Example (client emitting to server):
socket:Emit("HelloFromClient", "Hi Server, this is the client!")
On the server, you can broadcast to all clients:
socket:Emit("HelloFromServer", "Welcome to the game!")
For targeted messaging (server only), use EmitTo:
socket:EmitTo(targetPlayer, "TargetedMessage", "Hello from server")
3. Remote Procedure Calls (Call)
Clients can call server functions and await a response:
local serverTime = socket:Call("GetServerTime")
print("Client received server time:", serverTime)
On the server, handle the call like a normal event:
socket:On("GetServerTime", function(player)
return os.time() -- Returning the server time
end)
4. Broadcasting with Exception
The server can broadcast an event to all players except one using BroadcastExcept:
socket:BroadcastExcept(player, "StateUpdate", newState)
5. Measuring Latency
Measure the ping from client to server with the Ping method:
local latency = socket:Ping()
print("Client measured latency (seconds):", latency)
Module Overview (Socket.luau)
The Socket module abstracts Roblox RemoteEvents to create a socket-like interface.
It supports:
- On/Off/Once APIs: For registering and removing callbacks.
- Emit/EmitTo APIs: To send events both broadly and in a targeted manner.
- Call API: To perform remote procedure calls with automatic timeout handling.
- BroadcastExcept API: To send events to all players except a specified one.
- Ping API: To measure client-server latency.
For more detailed usage, inspect the code on github.
Happy coding!