Search code examples
tcpluaserverclient

Lua TCP/IP simple Client Server connection


I'm looking for a simple client-server connection in Lua. Due to bad online documentation I'm quite helpless. I found two threads here in stackoverflow but they didn't help much. Here is what I have so far:

Client:

local socket = require("socket")
local host, port = "192.168.100.47", 51515
local tcp = assert(socket.tcp())

tcp:connect(host, port);
tcp:send("hello world\n");

while true do
    local s, status, partial = tcp:receive()
    print(s or partial)
    if status == "closed" then
      break
    end
end

tcp:close()

Server:

local socket = require("socket")
local server = assert(socket.bind("*", 51515))
local tcp = assert(socket.tcp())

print(socket._VERSION)
print(tcp)

while 1 do

  local client = server:accept()

  line = client:receive()
  client:send("it works\n")

end

Solution

  • Here is a working client/server example, which is based on luasocket documentation and SO answers. If you have issues with getting it to work, you need to provide specific details about those issues.