Networking Sockets Example
These examples send a simple message from server to client and back, and should run with LuaJIT or LOVE2D. They can be found in the examples/socket_client/ and examples/socket_server/ folders of the repository. To run them, copy the luasteam and Steam API dlls into the folder and run with luajit, like ../../luajit/src/luajit main.lua from inside their folder.
Read more about how Steam networking works at their documentation. For the complete function reference, see ISteamNetworkingSockets.
Socket Client Example
1local Steam = require 'luasteam'
2
3local connection = nil
4
5print("Initializing client...")
6local ok = Steam.Init()
7local auth = Steam.NetworkingSockets.InitAuthentication()
8
9function Steam.NetworkingSockets.OnSteamNetAuthenticationStatus(data)
10 print('Auth status', data.m_eAvail, data.m_debugMsg)
11 if data.m_eAvail == 100 and not connection then
12 print("Connecting...")
13 local addr = Steam.newSteamNetworkingIPAddr {}
14 addr:ParseString("127.0.0.1:55556")
15 connection = Steam.NetworkingSockets.ConnectByIPAddress(addr, 0, nil)
16 end
17end
18
19local run = true
20function Steam.NetworkingSockets.OnSteamNetConnectionStatusChangedCallback(data)
21 if data.m_info.m_eState == Steam.k_ESteamNetworkingConnectionState_ClosedByPeer and data.m_hConn == connection then
22 print("Server closed connection.")
23 Steam.NetworkingSockets.CloseConnection(connection, 0, "", false)
24 run = false
25 end
26end
27
28local counter = 0
29while run do
30 Steam.RunCallbacks()
31
32 if connection then
33 local n, messages = Steam.NetworkingSockets.ReceiveMessagesOnConnection(connection, 32)
34
35 if n > 0 then
36 for j, m in ipairs(messages) do
37 print("Received message from connection " .. connection .. ": " .. m:GetData())
38 m:Release()
39 print("Sending message back...")
40 local data = "Hello server! This is the client! Thank you!"
41 Steam.NetworkingSockets.SendMessageToConnection(connection, data, #data, Steam.k_nSteamNetworkingSend_Reliable)
42 end
43 end
44 end
45end
46
47print("Shutting down...")
48Steam.Shutdown()