test-socket-server.nut 950 B

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