'How to connect external camera in flutter by Iowebsocketchannel ? Iowebsocketchannel isn't responding in the android emulator

I am new into flutter. Please help me find out why the android emulator isn't responding? I want to make an external camera (esp32-cam)as a client with a local Server I made and used the iowebsocketchannel package at flutter.The server code is :

const path = require('path');
const WebSocket = require('ws');


const express = require('express');
const app = express();
const HTTP_PORT = 8000;


const WS_PORT  = 8888;
const wsServer = new WebSocket.Server({port: WS_PORT}, ()=> console.log(`WS Server is listening at ${WS_PORT}`));

let connectedClients = [];
wsServer.on('connection', (ws, req)=>{
    console.log('Connected');
    connectedClients.push(ws);

    
    ws.on('error', console.log);
      
    ws.on('message', data => {
        connectedClients.forEach((ws,i)=>{
            if(ws.readyState === ws.OPEN){
                ws.send(data);
            }else{
                connectedClients.splice(i ,1);
            }
        })
    });
});

console.log(__dirname);
app.get('/client',(req,res)=>res.sendFile(path.resolve(__dirname, './client.html')));
app.listen(HTTP_PORT, ()=> console.log(`HTTP server listening at ${HTTP_PORT}`));

and the client code is :

<html>
    <head>
        <title>Client</title>
    </head>
    <body>
        <h1>The Stream </h1>
        <img src="">
        <script>
            const img = document.querySelector('img');
            const WS_URL = 'ws:///<ip4_address>:8888';
            const ws = new WebSocket(WS_URL);
            let urlObject;
            ws.onopen = () => console.log(`Connected to ${WS_URL}`);
            ws.onmessage = message => {
                const arrayBuffer = message.data;
                if(urlObject){
                    URL.revokeObjectURL(urlObject);
                }
                urlObject = URL.createObjectURL(new Blob([arrayBuffer]));
                img.src = urlObject;
            }
        </script>
    </body>
</html>

I am using android emulator Nexus 5 API 30 , when I try to use iowebsocketchannel to receieve a bitstream from the camera (esp32-cam),the emulator gives this error:

unhandled Exception: WebSocketChannelException: WebSocketChannelException: SocketException: Connection timed out

finally ,my flutter code is :

import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() {
  runApp( MyApp());
}

class MyApp extends StatelessWidget {
  // const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark(),
      title: "ESP32-Cam LocalServer",
      home: Home(
        channel: IOWebSocketChannel.connect('ws://192.168.64.239:8000/client'),
      ),
    );
  }
}

class Home extends StatefulWidget{
  final WebSocketChannel channel;

  const Home({Key? key,required this.channel}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("ESP32-Cam"),),
      body: Container(
        color: Colors.black,
        child: StreamBuilder(
          stream:  widget.channel.stream,
        builder: (context,snapshot){
          if(!snapshot.hasData)
            {
              return const Center(
                child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(Colors.white),),
              );
            }else{
            print("entereeed");
            return Image.memory(
                snapshot.data as Uint8List,
            );
          }
        },
        ),
      ),
    );
  }

}

The esp32-cam is using arduinowebsocket.h library with CamerawebServer example in arduino. Here is also the code I used :

#include "esp_camera.h"
#include <WiFi.h>
#include <ArduinoWebsockets.h>

 
// Select camera model
#define CAMERA_MODEL_AI_THINKER // Has PSRAM


#include "camera_pins.h"

const char* ssid = "mariam";
const char* password = "876543210";
const char* websocket_server_host = "192.168.64.239";
const uint16_t websocket_server_port = 8888;

using namespace websockets;
WebsocketsClient client;

//void startCameraServer();

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  Serial.println();

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 10000000;
  config.pixel_format = PIXFORMAT_JPEG;
  
  // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
  //                      for larger pre-allocated frame buffer.
  if(psramFound()){
    config.frame_size = FRAMESIZE_VGA;
    config.jpeg_quality = 40;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }
  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  } 

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

//  startCameraServer();

  Serial.print("Camera Ready! Use 'http://");
  Serial.print(WiFi.localIP());
  Serial.println("' to connect");

 while(!client.connect(websocket_server_host, websocket_server_port, "/")){
    delay(500);
    Serial.print(".");
  }
  Serial.println("Websocket Connected!");

 
}


void loop() {
//  // put your main code here, to run repeatedly:
//  delay(10000);

 camera_fb_t *fb = esp_camera_fb_get();
  if(!fb){
    Serial.println("Camera capture failed");
    esp_camera_fb_return(fb);
    return;
  }

  if(fb->format != PIXFORMAT_JPEG){
    Serial.println("Non-JPEG data not implemented");
    return;
  }

  client.sendBinary((const char*) fb->buf, fb->len);
  esp_camera_fb_return(fb);

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source