socketio server not connecting to ESP8266 - socket.io

I am facing problems while connecting to my SocketIo server through my ESP8266.
I have my ESP connected to my Wifi and my Node Server is running on localhost.
I have the following code in ESP8266
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <SocketIoClient.h>
//192.168.1.37 --My IP Address
SocketIoClient webSocket;
const char* ssid = "ssid"; // SSID
const char* password = "pass"; // Password
const char* host = "192.168.1.37"; // Server IP (localhost)
const int port = 8080; // Server Port
const char* url = "http://localhost:8080/test";
void event(const char * payload, size_t length) {
Serial.println("Message");
}
void setup() {
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500); // 5ms Delay
Serial.print(".");
}
Serial.print("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Connecting To Socket");
webSocket.on("event", event);
webSocket.begin("192.168.1.37", 8080);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
delay(3000); //Send a request every 3 seconds
webSocket.loop();
Serial.println("Retrying ....");
}
Also my Server side code is in JavaScript.
var io = socket(server);
io.on('connection', (socket) => {
console.log('made socket connection', socket.id);
socket.on("ESP", function(data){
socket.emit('Hi ESP, ESP called', data);
console.log("Socket Working !");
});
console.log('made socket connection', socket.id);
socket.on("connect", function(data){
socket.emit('Hi ESP connect called', data);
console.log("Socket Working !");
});
});
But i keep on receiving this output in the Serial Monitor.
Also there is no request received on my server.
11:37:09.729 -> ..........WiFi connected
11:37:14.129 -> IP address:
11:37:14.129 -> 192.168.1.13
11:37:14.129 -> Connecting To Socket
11:37:17.245 -> Retrying ....
11:37:17.245 -> [SIoC] Disconnected!
11:37:17.245 -> [SIoC] event disconnected not found. 1 events available
11:37:20.230 -> Retrying ....
11:37:20.230 -> [SIoC] Disconnected!
11:37:20.230 -> [SIoC] event disconnected not found. 1 events available

i have same issue
[SIoC] Disconnected!
[SIoC] Connected to url: /socket.io/?transport=websocket
[SIoC] Disconnected!
[SIoC] Disconnected!
[SIoC] Disconnected!
i change server side socket io config to this :
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
transports: ["websocket", "polling"],
credentials: true,
},
allowEIO3: true,
});
and Fix !

I have faced the same issue. It is fixed when I changed the socket.io version to ^2.3.0
Change the socket io version to ^2.3.0 in package.json, delete node modules and reinstall the packages using npm install command

I had the same issue and changed:
WiFi.begin(ssid, password);
to
WiFiMulti.addAP(ssid, pass);
and it connects fine.
PS: I used <SocketIOclient.h>

Related

canĀ“t emit via ethernet to my server on javascript?

hello, good day, I am making an example with a 5500 chip in esp32 with the socketioclient library, but when I want to send the json to my server, they are only left on the waiting list and I don't know what is happening to me, before all this an error message about invalid mbox appeared and I added the following line of code esp_netif_init(); and it was fixed, but once entering the loop the following happens:
serial monitor:
Starting WebServer on ESP32 with W5x00 using Ethernet_Generic Library with Large Buffer
Ethernet_Generic v2.4.0
[ETG] Default SPI pinout:
[ETG] MOSI: 23
[ETG] MISO: 19
[ETG] SCK: 18
[ETG] SS: 5
[ETG] =========================
[ETG] ESP32 setCsPin: 5
[ETG] W5100 init, using SS_PIN_DEFAULT = 22 , new ss_pin = 10 , W5100Class::ss_pin = 5
[ETG] Chip is W5500
[ETG] W5100::init: W5500, SSIZE = 8192
[ETG] Currently Used SPI pinout:
[ETG] MOSI: 23
[ETG] MISO: 19
[ETG] SCK: 18
[ETG] SS: 5
[ETG] =========================
Using mac index = 1
Connected! IP address: 192.168.10.147
Speed: 100 MB, Duplex: FULL DUPLEX, Link status: LINK
LLego a la parte de initwebsocket y task
termino inits
[SIoC] add packet 42["setRele",{"Dato":"hola"}]
[SIoC] add packet 42["getPrueba",{"name":"hola ese","SERVIDOR":"HOLA MUNDO"}]
[SIoC] Disconnected!
[SIoC] add packet 42["setRele",{"Dato":"hola"}]
[SIoC] add packet 42["getPrueba",{"name":"hola ese","SERVIDOR":"HOLA MUNDO"}]
[SIoC] Disconnected!
[SIoC] add packet 42["setRele",{"Dato":"hola"}]
[SIoC] add packet 42["getPrueba",{"name":"hola ese","SERVIDOR":"HOLA MUNDO"}]
[SIoC] Disconnected!
then the loop remains without emitting it just remains as shown above
sketch:
/****************************************************************************************************************************
WebServer.ino
Ethernet_Generic is a library for the W5x00 Ethernet shields trying to merge the good features of
previous Ethernet libraries
Built by Khoi Hoang https://github.com/khoih-prog/Ethernet_Generic
*****************************************************************************************************************************/
/*
The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno
and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53,
is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.
*/
#include "defines.h"
#include <SocketIoClient.h>
#include <Arduino_JSON.h>
#include <tcpip_adapter.h>
//TaskHandle_t Task1;
SocketIoClient socketIO;
//void Task1code( void * parameter ){
// Serial.print("Task1 is running on core ");
// Serial.println(xPortGetCoreID());
// while(1){
// socketIO.loop();
// delay(100);
// }
//}
//
//
void initWebSocket()
{
// server address, port and URL
socketIO.begin("192.168.10.59",8000);
// event handler for the event message
socketIO.on("asignacion",getresponse);
//socketIO.on("getPrueba",getresponse);
socketIO.loop();
delay(5000);
}
void getresponse(const char *payload, size_t length){
Serial.printf("response: ",payload);
String data = String(payload);
data.replace("\\","");
JSONVar dato = JSON.parse(data);
Serial.println(dato["litros"]);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
Serial.print("\nStarting WebServer on "); Serial.print(BOARD_NAME);
Serial.print(F(" with ")); Serial.println(SHIELD_TYPE);
Serial.println(ETHERNET_GENERIC_VERSION);
#if (USING_SPI2)
#if defined(CUR_PIN_MISO)
ETG_LOGWARN(F("Default SPI pinout:"));
ETG_LOGWARN1(F("MOSI:"), CUR_PIN_MOSI);
ETG_LOGWARN1(F("MISO:"), CUR_PIN_MISO);
ETG_LOGWARN1(F("SCK:"), CUR_PIN_SCK);
ETG_LOGWARN1(F("SS:"), CUR_PIN_SS);
ETG_LOGWARN(F("========================="));
#endif
#else
ETG_LOGWARN(F("Default SPI pinout:"));
ETG_LOGWARN1(F("MOSI:"), MOSI);
ETG_LOGWARN1(F("MISO:"), MISO);
ETG_LOGWARN1(F("SCK:"), SCK);
ETG_LOGWARN1(F("SS:"), SS);
ETG_LOGWARN(F("========================="));
#endif
#if defined(ESP32)
// You can use Ethernet.init(pin) to configure the CS pin
//Ethernet.init(10); // Most Arduino shields
//Ethernet.init(5); // MKR ETH shield
//Ethernet.init(0); // Teensy 2.0
//Ethernet.init(20); // Teensy++ 2.0
//Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet
//Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet
#endif
#ifndef USE_THIS_SS_PIN
#define USE_THIS_SS_PIN 5 //22 // For ESP32
#endif
ETG_LOGWARN1(F("ESP32 setCsPin:"), USE_THIS_SS_PIN);
// Must use library patch for Ethernet, EthernetLarge libraries
// ESP32 => GPIO2,4,5,13,15,21,22 OK with Ethernet, Ethernet2, EthernetLarge
// ESP32 => GPIO2,4,5,15,21,22 OK with Ethernet3
//Ethernet.setCsPin (USE_THIS_SS_PIN);
Ethernet.init (USE_THIS_SS_PIN);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
uint16_t index = millis() % NUMBER_OF_MAC;
// Use Static IP
//Ethernet.begin(mac[index], ip);
Ethernet.begin(mac[index]);
//SPIClass SPI2(HSPI);
//Ethernet.begin(mac[index], &SPI2);
// Just info to know how to connect correctly
// To change for other SPI
#if defined(CUR_PIN_MISO)
ETG_LOGWARN(F("Currently Used SPI pinout:"));
ETG_LOGWARN1(F("MOSI:"), CUR_PIN_MOSI);
ETG_LOGWARN1(F("MISO:"), CUR_PIN_MISO);
ETG_LOGWARN1(F("SCK:"), CUR_PIN_SCK);
ETG_LOGWARN1(F("SS:"), CUR_PIN_SS);
ETG_LOGWARN(F("========================="));
#else
ETG_LOGWARN(F("Currently Used SPI pinout:"));
ETG_LOGWARN1(F("MOSI:"), MOSI);
ETG_LOGWARN1(F("MISO:"), MISO);
ETG_LOGWARN1(F("SCK:"), SCK);
ETG_LOGWARN1(F("SS:"), SS);
ETG_LOGWARN(F("========================="));
#endif
Serial.print(F("Using mac index = "));
Serial.println(index);
Serial.print(F("Connected! IP address: "));
Serial.println(Ethernet.localIP());
if ( (Ethernet.getChip() == w5500) || (Ethernet.getAltChip() == w5100s) )
{
Serial.print(F("Speed: ")); Serial.print(Ethernet.speedReport());
Serial.print(F(", Duplex: ")); Serial.print(Ethernet.duplexReport());
Serial.print(F(", Link status: ")); Serial.println(Ethernet.linkReport());
}
Serial.println("LLego a la parte de initwebsocket y task");
Serial.println("termino inits");
// tcpip_adapter_init();
// for (int i = TCPIP_ADAPTER_IF_STA; i < TCPIP_ADAPTER_IF_MAX; i++) {
// if (tcpip_adapter_is_netif_up((tcpip_adapter_if_t)i))
// ESP_LOGI(TAG, "interface %i up ", i);
// else
// ESP_LOGI(TAG, "interface %i down ", i);
// }
esp_netif_init();//ojo con esta funcion https://gitter.im/espressif/arduino-esp32?at=607b291f06e2e024e85cdf50
initWebSocket();
// xTaskCreatePinnedToCore(Task1code,"Task1",10000,NULL,1,&Task1,0);
}
void loop()
{
//socketio.loop();
//socketIO.emit("getPrueba","{\"hello world\"}");
//socketIO.emit("plainString", "\"this is a plain string\"");
socketIO.emit("setRele","{\"Dato\":\"hola\"}");
delay(500);
//socketIO.emit("app","{\"name\":\"hola ese\",\"chava\":\"hola chava\"}");//esta libreria solo maneja archivos json
socketIO.emit("getPrueba","{\"name\":\"hola ese\",\"SERVIDOR\":\"HOLA MUNDO\"}");
//socketIO.emit("setData","{\"Dato\":\"hola\",\"Dato2\":\"Andre\"}");
//socketIO.on("get",getresponse);
delay(500);
socketIO.loop();
}
i only use two events to emit to the server they are setRele and getprueba as shown in the loop
server java script:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http,{allowEIO3: true ,cors: {origins: ['http://localhost:4200', 'http://localhost']}});
var port = process.env.PORT || 8080;
app.get('/', (req, res) => {
console.log("app works");
});
io.on('connection', (socket) => {
console.log(socket.id);
/**Catalogos */
// socket.emit("GetConfiguracion","{\"code\":\"ECOA-0179\",\"cambio\":\"0\",\"idRespuesta\":\"1\",\"Pines\":[{},{}]}");
// socket.emit("Reiniciar","{\"CodigoMDC\":\"ECOA-0179\"}");
// socket.emit("SetRelee","{\"code\":\"ECOA-0179\",\"f\":\"2022/04/26 03:51:33\",\"p\":\"26\",\"v\":\"1.00\"}");
socket.on("stateChanged", (params) => {
console.log(params); // x8WIv7-mJelg7on_ALbx
});
socket.on("getPrueba", (params) => {
console.log(params); // x8WIv7-mJelg7on_ALbx
});
socket.on("setRele", (params) => {
console.log(params); // x8WIv7-mJelg7on_ALbx
//socket.emit("SetRelee","{\"code\":\"ECOA-0179\",\"f\":\"2022/04/26 03:51:33\",\"p\":\"26\",\"v\":\"1.00\"}");
});
socket.on("ConfiguracionAplicada", (params) => {
console.log(params); // x8WIv7-mJelg7on_ALbx
});
socket.on('disconnect', () =>
{
console.log("Desconectado id: ",socket.id);
});
});
http.listen(port, () => {
console.log('listening on :' + port);
});
If someone could help me, it would be very helpful. Thank you. I'm new to ethernet connectivity. I hope you understand.

Why is this POST request from ESP32 to control KASA smart plug not working?

I am trying to communicate to a KASA HS103 smart plug using an HTTPS POST request sent via ESP32 (LoRa V2). For the actual POST content, I'm quite new to HTTP and have been following the instructions here: https://itnerd.space/2017/01/22/how-to-control-your-tp-link-hs100-smartplug-from-internet/
This is the POST request I am trying to send (with token & IDs modified):
URL: https://use1-wap.tplinkcloud.com/?token=fb2f7209-ATebDhHDOxB2wWc6wslPewO&appName=Kasa_Android&termID=1263f577-4387-4d3e-be79-705445d33bb08&appVer=1.4.4.607&ospf=Android+6.0.1&netType=wifi&locale=en_US
{
"method":"passthrough",
"params":{
"deviceId":"80068FEB5A735A5BB187B4EC309EF1BE1D6D8997",
"requestData":"{\"system\":{\"set_relay_state\":{\"state\":1}}}"
}
}
This will turn on the smart plug. I have verified that the POST request itself works, with both an online API tester (https://reqbin.com/) and through cURL on my MacBook.
I retrieved the URL token and device ID by authenticating with TP-Link server using my credentials through the API tester (also in the instructions linked above).
However, I am unable to control the smart plug when sending with ESP32. I am writing and compiling through the Arduino IDE, using the Heltec framework / libraries. Here is my code (started with the code from Rui Santos here and modified for my application):
/*
Rui Santos
Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
const char* ssid = "XXXXX";
const char* password = "XXXXX";
//Your Domain name with URL path or IP address with path
const char* serverName = "https://use1-wap.tplinkcloud.com/?token=fb2f7209-ATebDhHDOxB2wWc6wslPewO&appName=Kasa_Android&termID=1263f577-4387-4d3e-be79-705445d33bb08&appVer=1.4.4.607&ospf=Android+6.0.1&netType=wifi&locale=en_US HTTP/1.1";
const int port = 443;
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
//Send an HTTP POST request every 10 minutes
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClientSecure *client = new WiFiClientSecure;
if (client) {
Serial.println("Client Created!");
//client -> setCACert(rootCACertificate);
{
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(*client, serverName);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
//int httpResponseCode = http.POST("{\"api_key\":\"tPmAT5Ab3j7F9\",\"sensor\":\"BME280\",\"value1\":\"24.25\",\"value2\":\"49.54\",\"value3\":\"1005.14\"}");
int httpResponseCode = http.POST("{\"method\":\"passthrough\", \"params\": {\"deviceId\": \"80068FEB5A735A5BB187B4EC309EF1BE1D6D8997\", \"requestData\": \"{\"system\":{\"set_relay_state\":{\"state\":0}}}\" }}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.print("HTTP String: ");
Serial.println(payload);
// Free resources
http.end();
}
delete client;
} else {
Serial.println("Unable to create client");
}
} else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}
Here is the output from the serial terminal:
Connected to WiFi network with IP Address: 192.168.X.XXX
Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.
Client Created!
HTTP Response code: 200
HTTP String: {"error_code":-10100,"msg":"JSON format error"}
The smart plug does not turn off when uploading and running on ESP32.
Doing a quick search online for POST response codes, receiving 200 seems to mean the request was processed and OK, yet the error code is negative and message is "JSON format error".
Any ideas why this POST request is not working? Or anything I should try to get more info?
Thanks in advance!
Digging into "JSON format error" - turns out I had an extra "" around the 'requestData' value which parsed fine in cURL but could not be understood when sending raw through ESP32.
Removing those quotes fixed the problem and now I'm able to send POST requests successfully.
Here is the working code now:
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>
const char* ssid = "XXXXX";
const char* password = "XXXXX";
//Your Domain name with URL path or IP address with path
const char* serverName = "https://use1-wap.tplinkcloud.com/?token=fb2f7209-ATebDhHDOxB2wWc6wslPewO&appName=Kasa_Android&termID=1163f577-4288-4d3d-be69-705445d33ba08&appVer=1.4.4.607&ospf=Android+6.0.1&netType=wifi&locale=en_US HTTP/1.1";
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
//Send an HTTP POST request every 10 minutes
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClientSecure *client = new WiFiClientSecure;
if (client) {
{
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(*client, serverName);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST("{\"method\":\"passthrough\",\"params\":{\"deviceId\":\"80068FEB3A733B5BB287B4EC309FE1BE1D7D8997\",\"requestData\":{\"system\":{\"set_relay_state\":{\"state\":1}}}}}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.print("HTTP String: ");
Serial.println(payload);
// Free resources
http.end();
}
delete client;
} else {
Serial.println("Unable to create client");
}
} else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}

Arduino(ESP8266) to laravel websocket channel subscription problem

i'm working on an IoT project which needs to connect to a laravel based socket server.
on laravel side all things are working just as should be but the problem is in arduino side which is a ESP8266 module being program by Arduino IDE.
i want to use Links2004/arduinoWebSockets library to connect to server.
it connects but i can't determine on which channel it should be.
is there any way on this library to tell the channel device should be on?
I gratefully appreciate any help :)
Arduino Test Code:
/*
Esp8266 Websockets Client
This sketch:
1. Connects to a WiFi network
2. Connects to a Websockets server
3. Sends the websockets server a message ("Hello Server")
4. Prints all incoming messages while the connection is open
Hardware:
For this sketch you only need an ESP8266 board.
Created 15/02/2019
By Gil Maimon
https://github.com/gilmaimon/ArduinoWebsockets
*/
#include <ArduinoWebsockets.h>
#include <ESP8266WiFi.h>
const char* ssid = "****"; //Enter SSID
const char* password = "******"; //Enter Password
const char* websockets_server_host = "xxx.xxx.xxx.xxx"; //Enter server adress -- serverip_or_name
const uint16_t websockets_server_port = 6001; // Enter server port
bool connected;
using namespace websockets;
WebsocketsClient client;
void setup() {
Serial.begin(115200);
// Connect to wifi
WiFi.begin(ssid, password);
// Wait some time to connect to wifi
for(int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
Serial.print(".");
delay(1000);
}
// Check if connected to wifi
if(WiFi.status() != WL_CONNECTED) {
Serial.println("No Wifi!");
return;
}
Serial.println("Connected to Wifi, Connecting to server.");
// try to connect to Websockets server
connected = client.connect(websockets_server_host, websockets_server_port, "/app/ab_key");
if(connected) {
Serial.println("Connecetd!");
client.send("Hello Server");
} else {
Serial.println("Not Connected!");
}
// run callback when messages are received
client.onMessage([&](WebsocketsMessage message) {
Serial.print("Got Message: ");
Serial.println(message.data());
});
}
void loop() {
if(connected) {
Serial.println("Connecetd!");
client.send("Hello Server");
} else {
connected = client.connect(websockets_server_host, websockets_server_port, "/app/ab_key");
Serial.println("try!");
}
// let the websockets client check for incoming messages
if(client.available()) {
client.poll();
}
delay(500);
}
terminal view of laravel websocket: laravel websocket

Connect WebSocket to a listening Titanium Ti.Network.Socket.TCP?

I'm trying to connect a WebSocket in the browser to a listening Socket server on a Titanium-based iOS app.
The device and browser machine are on the same wireless router, but I have only been able to get
[16:01:09.282] Firefox can't establish a connection to the server at ws://192.168.0.190:8080/.
Is this something to do with the protocol "ws://" ? How does the Titanium Socket listener know to expect that protocol?
This is my Titanium socket code:
var hostname = Ti.Platform.address;
//Create a socket and listen for incoming connections
var listenSocket = Ti.Network.Socket.createTCP({
host : hostname,
port : 8080,
accepted : function(e) {
// This where you would usually store the newly-connected socket, e.inbound
// so it can be used for read / write operations elsewhere in the app.
// In this case, we simply send a message then close the socket.
Ti.API.info("Listening socket <" + e.socket + "> accepted incoming connection <" + JSON.stringify(e.inbound) + ">");
e.inbound.write(Ti.createBuffer({
value : 'Hi from iOS.\r\n'
}));
// e.inbound.close();
// close the accepted socket
},
error : function(e) {
Ti.API.error("Socket <" + e.socket + "> encountered error when listening");
Ti.API.error(" error code <" + e.errorCode + ">");
Ti.API.error(" error description <" + e.error + ">");
}
});
// Starts the socket listening for connections, does not accept them
listenSocket.listen();
Ti.API.info("Listening now...");
// Tells socket to accept the next inbound connection. listenSocket.accepted gets
// called when a connection is accepted via accept()
Ti.API.info("Calling accept.");
listenSocket.accept({
timeout : 10000
});
And here is the code in the browser:
function sensorClient(host, port) {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://" + host + ":" + port);
ws.onopen = function () {
// Web Socket is connected, send data using send()
ws.send("hi from the browser");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message received..." + received_msg);
};
ws.onclose = function () {
// websocket is closed.
alert("Connection is closed...");
};
}
else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}

Multicast UDP packets to Multiple Interfaces (Multiple network adapters) in the system using boost asio

I want to multicast data to the all the network cards present in the system using boost asio(udp).
Can anyone help me in understanding how this can be done.I have created following example but its not working.The stream data send to each socket is getting mixed and the output is a mix of all sockets data on a single interface.
//e.g
Assume
data send to Interface1 is "Abcd"(Note: each interface has a separate socket)
data send to Interface2 is "xyz"
Then the output is only received from Interface1 ,the out stream is mixed(e.g "abxycdz" or "abxcdzy" etc)
Please help me in understanding the issue.
for(int i=0;i<NoOfInterfcaes;i++)
{
Open("229.1.1.1",1000,sNetInterfcaeAddList[i],false);
}
....................................
for(int i=0;i<NoOfInterfcaes;i++)
{
send(dataBuffer,len);
}
....................................
void Open(std::string &multicastIp,int nPort, std::string& sNetInterfcaeIpAdd,bool broadcast)
{
m_sNetInterfcaeIpAdd=sNetInterfcaeIpAdd;
m_sMulticastIp=multicastIp;
m_nport = nPort;
m_broadcast = broadcast ;
// try and open socket
const ip::udp::resolver::query queryIF( ip::udp::v4(),multicastIp.c_str(), nPort );
///resolve the connection
m_resolver.async_resolve(queryIF,
boost::bind(&handle_resolve, this,
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
void handle_resolve(const boost::system::error_code& err,
boost::asio::ip::udp::resolver::iterator endpoint_iterator)
{
if (!err)
{
//make a connection
m_socket.async_connect(*endpoint_iterator,
boost::bind(&handle_connect, this,
boost::asio::placeholders::error, endpoint_iterator));
}
else
{
//error message
}
}
void handle_connect(const boost::system::error_code& error,
boost::asio::ip::udp::resolver::iterator endpoint_iterator)
{
if (!error)
{
//Select the network adaptor
m_socket.set_option( boost::asio::ip::multicast::outbound_interface( boost::asio::ip::address_v4::from_string(m_sNetInterfcaeIpAdd)));
m_socket.set_option( boost::asio::ip::multicast::enable_loopback(false));
if(m_broadcast)
{
boost::asio::socket_base::broadcast option(true);
m_socket.set_option(option);
}
}
else if (endpoint_iterator != boost::asio::ip::udp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
m_socket.close();
//try to connect
m_socket.async_connect(*endpoint_iterator,
boost::bind(&handle_connect, this,
boost::asio::placeholders::error, endpoint_iterator));
}
else
{
//
}
}
You use this one socket per adapter, binding each to its adapter using the code from this question: Boost asio socket multicast to a specific ethernet interface

Resources