test-socket.lua 968 B

123456789101112131415161718192021222324252627
  1. -- load namespace
  2. local socket = require("socket.core")
  3. -- create a TCP socket and bind it to the local host, at any port
  4. --local server = assert(socket.bind("*", 0))
  5. local server = socket.tcp();
  6. --server.bind("*", 0);
  7. server:setoption("reuseaddr", true);
  8. server:bind("*", 0);
  9. server:listen();
  10. -- find out which port the OS chose for us
  11. local ip, port = server:getsockname()
  12. -- print a message informing what's up
  13. print("Please telnet to localhost on port " .. port)
  14. print("After connecting, you have 10s to enter a line to be echoed")
  15. -- loop forever waiting for clients
  16. while 1 do
  17. -- wait for a connection from any client
  18. local client = server:accept()
  19. -- make sure we don't block waiting for this client's line
  20. --client:settimeout(10)
  21. -- receive the line
  22. local line, err = client:receive()
  23. -- if there was no error, send it back to the client
  24. if not err then client:send(line .. "\n") end
  25. -- done with client, close the object
  26. client:close()
  27. end