aboutsummaryrefslogtreecommitdiff
path: root/reference/networking.md
blob: 087dd9555c91dd13a17185f1b8ce0fba11f1ccc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Networking example

A simple example of networking, ripped straight from the brok[en]gine test suite.


### Client

	local has_ponged = false
	local socket = net.newsocket(net.PAIR)
	socket:bind("tcp://127.0.0.1:5555")
	function socket:receive(stream)
		print("socket receive triggered")
		has_ponged = true
		local message = stream:readstring()
		assert(message == "ping")
		socket:send(function(stream2)
			stream2:writestring("pong")
		end)
	end
	local i = os.time()
	function GAME.tick()
		if has_ponged then
			GAME.exit()
		end
		if i - os.time() > 5 then
			error("Failed")
		end
	end

### Server

	local socket = net.newsocket(net.PAIR)
	socket:connect("tcp://127.0.0.1:5555")
	function socket:receive(stream)
		local message = stream:readstring()
		assert(message == "pong")
	end
	socket:send(function(stream)
		stream:writestring("ping")
	end)