Lua TCP/IP simple Client Server connection

26,593

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.

Share:
26,593
Speedbird
Author by

Speedbird

Updated on April 17, 2021

Comments

  • Speedbird
    Speedbird over 1 year

    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
    
    • Paul Kulchenko
      Paul Kulchenko almost 6 years
      What's your question?
    • Speedbird
      Speedbird almost 6 years
      I want to communicate between this two servers but I don't know how it works and I also can't find much in the internet. So the question is: how to write a simple TCP server and client with LUA?
    • Paul Kulchenko
      Paul Kulchenko almost 6 years
      What's the problem with the example you already have?