Teens41-Server.ino 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Teensy41 Websockets Server (using NativeEthernet)
  3. This sketch:
  4. 1. Connects to a ethernet network
  5. 2. Starts a websocket server on port 80
  6. 3. Waits for connections
  7. 4. Once a client connects, it wait for a message from the client
  8. 5. Echoes the message to the client
  9. 6. Closes the connection and goes back to step 3
  10. Note:
  11. Make sure you share your computer's internet connection with the Teensy
  12. via ethernet.
  13. Libraries:
  14. To use this sketch install
  15. * TeensyID library (https://github.com/sstaub/TeensyID)
  16. * NativeEthernet (https://github.com/vjmuzik/NativeEthernet)
  17. Hardware:
  18. For this sketch you need a Teensy 4.1 board and the Teensy 4.1 Ethernet Kit
  19. (https://www.pjrc.com/store/ethernet_kit.html).
  20. */
  21. #include <NativeEthernet.h>
  22. #include <ArduinoWebsockets.h>
  23. #include <TeensyID.h>
  24. using namespace websockets;
  25. WebsocketsServer server;
  26. // We will set the MAC address at the beginning of `setup()` using TeensyID's
  27. // `teensyMac` helper.
  28. byte mac[6];
  29. // Enter websockets server port.
  30. const uint16_t port = 80;
  31. void setup() {
  32. // Set the MAC address.
  33. teensyMAC(mac);
  34. // Start Serial and wait until it is ready.
  35. Serial.begin(9600);
  36. while (!Serial) {}
  37. // Connect to ethernet.
  38. if (Ethernet.begin(mac)) {
  39. Serial.println("Ethernet connected");
  40. } else {
  41. Serial.println("Ethernet failed");
  42. }
  43. // Start websockets server.
  44. server.listen(port);
  45. if (server.available()) {
  46. Serial.print("Server available at ws://");
  47. Serial.print(Ethernet.localIP());
  48. // Also log any non default port.
  49. if (port != 80) Serial.printf(":%d", port);
  50. Serial.println();
  51. } else {
  52. Serial.println("Server not available!");
  53. }
  54. }
  55. void loop() {
  56. WebsocketsClient client = server.accept();
  57. if (client.available()) {
  58. Serial.println("Client connected");
  59. // Read message from client and log it.
  60. WebsocketsMessage msg = client.readBlocking();
  61. Serial.print("Got Message: ");
  62. Serial.println(msg.data());
  63. // Echo the message.
  64. client.send("Echo: " + msg.data());
  65. // Close the connection.
  66. client.close();
  67. Serial.println("Client closed");
  68. }
  69. }