Personal tools

Lua/Tutorials/Using network events

From JC2-MP Documentation

< Lua‎ | Tutorials
Jump to: navigation, search

There are two basic parts of using Network: sending events and receiving events.

  • Server
    • Can send network events to clients
    • Can receive network events from clients
  • Client
    • 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)


Events:Subscribe("KeyUp", function(args)
	if args.key == VirtualKey.Space then
		Network:Send("MyNetworkEventName", "Hello")

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())


Network:Subscribe("Greet", function(message)
	Chat:Print("The server says: "..message, Color.LightYellow)

Note: We use the ClientModuleLoad event here instead of PlayerJoin. If you try to use PlayerJoin, the client may not have loaded their scripts yet and nothing will happen.


Server/client Network:Send

  • Server
    • Network:Send(player, event_name)
    • Network:Send(player, event_name, argument)
  • Client
    • Network:Send(event_name)
    • 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.

Other server-side Network functions

  • Network:Broadcast - Like Network:Send, but for all players.
  • Network:SendToPlayers - Like Network:Broadcast, but only for the specified table of players.
  • Network:SendNearby - Sends to all players near the specified player. The distance is dependent on the stream distance set in config.lua.