Lua/Tutorials/Using network events
From JC2-MP Documentation
There are two basic parts of using Network: sending events and receiving events.
- Can send network events to clients
- Can receive network events from clients
- Can send network events to the server
- Can receive network events from the server
- Can not send or receive from other clients
Client to server example: client tells the server when the spacebar is pressed
Network:Subscribe("MyNetworkEventName", function(message, player) print(tostring(player).." pressed the spacebar and says "..message) end)
Events:Subscribe("KeyUp", function(args) if args.key == VirtualKey.Space then Network:Send("MyNetworkEventName", "Hello") end end)
Server to client example: greet the player on join (or module load)
Events:Subscribe("ClientModuleLoad", function(args) Network:Send(args.player, "Greet", "Welcome to the server, "..args.player:GetName()) end)
Network:Subscribe("Greet", function(message) Chat:Print("The server says: "..message, Color.LightYellow) end)
- Network:Send(player, event_name)
- Network:Send(player, event_name, argument)
- Network:Send(event_name, argument)
It works very similarly to Events:Subscribe. There are two versions: one for functions, and one for class functions.
- Network:Subscribe(event_name, function)
- Network:Subscribe(event_name, instance, function)
On the server, the function you give to Network:Subscribe can have two parameters: the argument and the player who sent the network event. Or sometimes just one, depending on if the client sent an argument or not. (This behaviour is questionable, but there's not much that can be done at this stage.) So, your function can look like the following:
function() end function(arg) end function(player) end function(arg, player) end
On the client, there is no second argument to worry about.