Arduino Socket.io Communicate

Ahmad Akanci picture Ahmad Akanci · Oct 10, 2016 · Viewed 9k times · Source

How can i send Data from Socket.io (NodeJs Server) to arduino ? I have a ESP8266 Wifi Shield , Can i send and receive data ? If i can there is any basic example for it ? How can i use the Arduino Socket Client ? I find like this example

Can I Use like this ?

#include <SPI.h>
#include <Ethernet.h>

#include "SocketIOClient.h"

SocketIOClient client;

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char hostname[] = "";

// Socket.io "chat_message" event handler
void chat_message(EthernetClient ethclient, char *data ){
  Serial.print("Message : ");
  Serial.println(data);
}

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac);
  Serial.print("Arduino is on ");
  Serial.println(Ethernet.localIP());

  if(client.connect(hostname, 3000, "socket.io", "/chat_room")) {
    Serial.println("Socket.IO connected !");
  } else {
    Serial.println("Socket.IO not connected.");
  }

  //Event hanlders
  client.setEventHandler("chat_message",  chat_message);

  //Say hello! to the server
  client.emit("chat_message", "Arduino here, hello!");
}

void loop() {
  client.monitor();
}

Answer

cagdas picture cagdas · Oct 11, 2016

Socket.IO is an API for WebSockets and most of Websocket libraries are supporting it.

I am pretty happy with this most contributed Arduino WebSocket library and it also supports Socket.IO. Here is your Socket.IO example.

Here is a heartbeat message type of socket.io implementaiton from the example:

if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
    heartbeatTimestamp = now;
    // socket.io heartbeat message
    webSocket.sendTXT("2");
}