1

nodemcu ファームウェアを使用して、ESP-12 で小さな Web サーバーを実行しています。

sv=net.createServer(net.TCP,10)

sv:listen(80,function(c)

    c:on("receive", function(c, pl)

        if(string.find(pl,"GET / ")) then
            print("Asking for index")
            c:send("Line 1")
            c:send("Line 2")
            c:send("Line 3")
            c:close()
        end

    end)
  c:on("sent",function(conn) 
    print("sended something...")
  end)
end)

最初の送信後に接続が閉じられているようです。ブラウザには「1行目」のテキストしか表示されず、2行目と3行目は表示されず、シリアルコンソールには「何かを送信しました」というテキストが1回だけ表示されます。 close ステートメントにコメントを付けて、接続をタイムアウトさせても、動作は変わりません。ここで何が欠けていますか?

4

2 に答える 2

1

send を複数回使用できるとは思いません。ESP8266 の 1 つをサーバーとして使用するときは常に、バッファー変数を使用します。

sv=net.createServer(net.TCP,10)
-- 'c' -> connection, 'pl' -> payload
sv:listen(80,function(c)

    c:on("receive", function(c, pl)

        if(string.find(pl,"GET / ")) then
            print("Asking for index")
            local buffer = ""
            buffer = buffer.."Line 1"
            buffer = buffer.."Line 2"
            buffer = buffer.."Line 3"
            c:send(buffer)
            c:close()
        end

    end)
    c:on("sent",function(c)
        print("sended something...")
    end)
end)

編集:ドキュメントを再度読んだ後send、コールバック関数で別の引数を取ることができます。複数の送信コマンドを使用することができます。でも試したことはありません:(。

編集 2: 送信する文字列が非常に長い場合は、table.concatを使用することをお勧めします。

于 2015-11-22T06:58:20.583 に答える
1

net.socket :send()のドキュメントには、ここで繰り返す良い例があります。

srv = net.createServer(net.TCP)

function receiver(sck, data)
  local response = {}

  -- if you're sending back HTML over HTTP you'll want something like this instead
  -- local response = {"HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"}

  response[#response + 1] = "lots of data"
  response[#response + 1] = "even more data"
  response[#response + 1] = "e.g. content read from a file"

  -- sends and removes the first element from the 'response' table
  local function send(localSocket)
    if #response > 0 then
      localSocket:send(table.remove(response, 1))
    else
      localSocket:close()
      response = nil
    end
  end

  -- triggers the send() function again once the first chunk of data was sent
  sck:on("sent", send)

  send(sck)
end

srv:listen(80, function(conn)
  conn:on("receive", receiver)
end)
于 2017-02-12T20:53:49.017 に答える