Problems sending websocket message from esp8266 as client

22 Views Asked by At

can someone help with websockets? i want to use an esp8266 as a websocketclient to send data to another esp8266 as a websocketserver

the server is at ws://192.168.4.1/ws port:80 (note that /ws in ws://192.168.4.1/ws is important)

this is the websocketclient code for the esp8266 that I cannot get it to work

#include <ESP8266WiFi.h>
#include <WebSocketsClient.h>

const char* ssid = "ssidexample";
const char* password = "password";
const char* webSocketServerIP = "192.168.4.1";
const int webSocketServerPort = 80; // Change this to the appropriate port

WebSocketsClient webSocket;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to Wi-Fi...");
  }

  Serial.println("Connected to Wi-Fi");
  webSocket.begin(webSocketServerIP, webSocketServerPort, "/ws");
  webSocket.onEvent(webSocketEvent);
}

void loop() {
  webSocket.loop();

  // Send the "version" message to the WebSocket server
  webSocket.sendTXT("version");
}

void webSocketEvent(WStype_t type, uint8_t* payload, size_t length) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.println("WebSocket disconnected");
      break;
    case WStype_CONNECTED:
      Serial.println("WebSocket connected");
      break;
    case WStype_TEXT:
      Serial.print("Received response: ");
      Serial.println((char*)payload);
      break;
    default:
      break;
  }
}

i've tried running this code from my computer as a websocketclient, and it worked flawlessly, here is the working python code.

import asyncio
import websockets

async def send_version():
    uri = "ws://192.168.4.1/ws"
    async with websockets.connect(uri) as websocket:
        await websocket.send("version")  # Send the message
        response = await websocket.recv()  # Receive the response
        print(f"Received response: {response}")

# Run the WebSocket client
asyncio.get_event_loop().run_until_complete(send_version())

I tried using AI generated code, and it still doesnt work

0

There are 0 best solutions below