-
Notifications
You must be signed in to change notification settings - Fork 23
Plugin network messages
Plugin network messages provide an easier way to setup and deal with network messages in plugins.
To register network messages for a plugin, you need to use the function Plugin:AddNetworkMessage()
, in the Plugin:SetupDataTable()
method. This method is also used to set up data table variables. Make sure this is in the shared.lua
file of the plugin.
There is a significant difference between data table variables and network messages. Data table variables are automatically sent to all players and synced when changed. This is useful for networking things like gamestates, settings flags, but not useful for initiating a one time action. Network messages are sent only once, and only to the players that they are set to send to at the time of sending.
function Plugin:SetupDataTable()
self:AddNetworkMessage( "ServerTest", { Number = "integer (0 to 10)" }, "Client" )
self:AddNetworkMessage( "ClientTest", { String = "string (10)" }, "Server" )
end
The arguments to Plugin:AddNetworkMessage()
are:
- The name to give this network message, this is used later to send it, and to set up the receiving function.
- The table of data the network message will contain, this table is identical to those used in
Shared.RegisterNetworkMessage()
. - The environment that's going to receive this message, either "Server" or "Client".
To send a network message you have set up, use the Plugin:SendNetworkMessage()
method.
function Plugin:UpdateNumber( Num )
self:SendNetworkMessage( nil, "ServerTest", { Number = Num }, true )
end
The arguments to Plugin:SendNetworkMessage()
on the server side are:
- The client(s) to send the message to. Either a ServerClient object, an array of ServerClients, or nil to send to everyone.
- The name of the network message, the same one used when adding it.
- The table of data to send.
- Whether to send the data reliably.
function Plugin:UpdateString( String )
self:SendNetworkMessage( "ClientTest", { String = String }, true )
end
The arguments to Plugin:SendNetworkMessage()
on the client side are:
- The name of the network message, the same one used when adding it.
- The table of data to send.
- Whether to send the data reliably.
To receive a network message, make a function on the plugin's table, in the environment you set it to be received, called Receive<Name>
. <Name>
is the name of the message set when you added it.
if Server then
function Plugin:ReceiveClientTest( Client, Data )
self.String = Data.String
end
elseif Client then
function Plugin:ReceiveServerTest( Data )
self.Number = Data.Number
end
end
When receiving on the server, there are two arguments, the client who sent the message, and the data. When receiving on the client, the only argument is the table of data from the network message.