socket.io-client-dart icon indicating copy to clipboard operation
socket.io-client-dart copied to clipboard

Unable to connect to socket.io server

Open Jarrod-Herbert opened this issue 3 years ago • 13 comments

I'm trying to get a Dart application communicating with my Node.js socket.io server, but am not having much luck.

Below I've posted the javascript of my index.js for node.js, the main.dart file for my console application, and both the node.js and dart console outputs.

For testing, I started the node.js server on my Linux server, and then connected to it using the below index.html. I was able to successfully send a message and it was displayed in the console as expected. However, running the dart app pointing at the same socket.io server does not appear to work.

Is there something here that I'm just missing? Or is it not working as intended. Thanks -

index.js of node.js socket.io server:

const http = require('http').createServer();

const io = require('socket.io')(http, {
    cors: { origin: "*" }
});

io.on('connection', (socket) => {
    console.log('a user connected');

    socket.on('message', (message) =>     {
        console.log(message);
        io.emit('message', `${socket.id.substr(0,2)} said ${message}` );   
    });
});

http.listen(3000, () => console.log('listening on http://vaguelyfebruary.com:3000') );

index.html for validating the socket.io is on.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.socket.io/socket.io-3.0.0.js"></script>
    <script defer src="app.js"></script>
</head>
<body>

    <ul>
        
    </ul>

    <input placeholder="message">
    <button>Send</button>
    
</body>
</html>

app.js that is imported by index.html

const socket = io('ws://vaguelyfebruary.com:3000');


socket.on('message', text => {
    const el = document.createElement('li');
    el.innerHTML = text;
    document.querySelector('ul').appendChild(el)

});

document.querySelector('button').onclick = () => {

    const text = document.querySelector('input').value;
    socket.emit('message', text)
    
}

Dart main.dart file:

import 'package:socket_io_client/socket_io_client.dart' as IO;

main() {
  // Dart client
  print('starting');
  IO.Socket socket = IO.io('http://vaguelyfebruary:3000', <String, dynamic>{
    'transports': ['websocket']
  });
  socket.onConnect((_) {
    print('connect');
    socket.emit('message', 'test');
  });
  socket.on('event', (data) => print(data));
  socket.onDisconnect((_) => print('disconnect'));
  socket.on('fromServer', (_) => print(_));
  print('end');
}

Dart pubsec.yaml:

name: taskman_socket
description: A sample command-line application.
# version: 1.0.0
# homepage: https://www.example.com
environment:
  sdk: '>=2.10.0 <3.0.0'

#dependencies:
#  path: ^1.7.0
dev_dependencies: null
dependencies:
  socket_io_client: ^0.9.12

node.js console output:

[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
listening on http://vaguelyfebruary.com:3000
a user connected
Sent from index.html pointing at http://vaguelyfebruary.com

Dart console output:

Connecting to VM Service at ws://127.0.0.1:62786/hN75r-GapHY=/ws
starting
end

Jarrod-Herbert avatar Apr 09 '21 04:04 Jarrod-Herbert

FYI: https://github.com/rikulo/socket.io-client-dart#version-info

jumperchen avatar Apr 09 '21 04:04 jumperchen

To make sure I'm understanding, with my dependency of socket_io_client: ^0.9.12 in Dart, I should be using [email protected] (the most up to date 2.* version) on my node.js server? Is that accurate?

Jarrod-Herbert avatar Apr 09 '21 04:04 Jarrod-Herbert

Yes, or you can use socket.io-client-dart 2.x version with your current 3.0.0 socket.io server.

jumperchen avatar Apr 09 '21 06:04 jumperchen

Thank you for being patient with me while I try and get this working!

I've updated my pubsec.yaml to point at the 2.x version of socket.io-client-dart, as shown below:

dependencies:
  socket_io_client: ^2.0.0-beta.3-nullsafety.0

I've also recreated my node.js server, to explicitly point it at a 3.x version of socket.io. Below is the output of npm list.

└─┬ [email protected]
  ├── @types/[email protected]
  ├── @types/[email protected]
  ├── @types/[email protected]
  ├── [email protected] deduped
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  ├─┬ [email protected]
  │ ├── [email protected] deduped
  │ ├── [email protected] deduped
  │ ├── [email protected]
  │ ├─┬ [email protected]
  │ │ ├── [email protected]
  │ │ └── [email protected] deduped
  │ ├─┬ [email protected]
  │ │ └── [email protected]
  │ ├─┬ [email protected]
  │ │ └── [email protected]
  │ └── [email protected]
  ├── [email protected]
  └─┬ [email protected]
    ├── @types/[email protected]
    ├── [email protected]
    └─┬ [email protected]
      └── [email protected]

Following these changes I am still seeing the same results; index.html successfully connects, but my main.dart does not make any indication that it's trying to connect. Based on Issue #147, I tried using [email protected], no luck with that either.

Jarrod-Herbert avatar Apr 09 '21 13:04 Jarrod-Herbert

I've tried to strip this down to the absolute bare-bones application. Currently I'm only looking to establish a WebSocket connection from a dart console app, to a Node.JS server. Things can be built up from there, but right now I cannot establish a connection at all.

Node.JS server

I've got Node.JS running with the below code on a Linux host, URL to this is vaguelyfebruary.com.

NPM List

~/socket_io$ npm list
[email protected] /home/taskman/socket_io
├── [email protected]
└── [email protected]

index.js

const express = require("express");
const socket = require("socket.io");

// App setup
const PORT = 5000;
const app = express();
const server = app.listen(PORT, function () {
  console.log(`Listening on port ${PORT}`);
  console.log(`http://localhost:${PORT}`);
});

// Static files
app.use(express.static("public"));

// Socket setup
const io = socket(server);

io.on("connection", function (socket) {
  console.log("Made socket connection");
});

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Socket.io simple chat</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <div class="container">
      <p>Hello</p>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.0/socket.io.js"></script>
    <script src="main.js"></script>
  </body>
</html>

main.js

const socket = io();

Dart Console App

The Dart application trying to connect to the WebSocket on vaguelyfebruary.com:5000;

main.dart

import 'package:socket_io_client/socket_io_client.dart' as IO;

void main() {
  // Dart client
  IO.Socket socket = IO.io('http://vaguelyfebruary.com:5000');
  socket.onConnect((_) {
    print('connect');
    socket.emit('msg', 'test');
  });
  socket.on('event', (data) => print(data));
  socket.onDisconnect((_) => print('disconnect'));
  socket.on('fromServer', (_) => print(_));
}

pubsec.yaml

name: socket_io
description: A sample command-line application.
# version: 1.0.0
# homepage: https://www.example.com

environment:
  sdk: '>=2.10.0 <3.0.0'

dependencies:
  socket_io_client: ^2.0.0-beta.3-nullsafety.0

dev_dependencies:
  pedantic: ^1.9.0
  test: ^1.14.4

Jarrod-Herbert avatar Apr 14 '21 15:04 Jarrod-Herbert

Hi! I'm trying to connect to my server but I can't. I'm using the chat example of socketIO (https://socket.io/get-started/) I wrote a basic test to check if it connects properly, but always fails

  test('Autoconnect to socket io', () async {
    IO.Socket socket = IO.io('http://192.168.1.11:3000');

    expect(socket.connected, true);
  });

Octonove avatar Apr 28 '21 00:04 Octonove

Hi! I'm trying to connect to my server but I can't. I'm using the chat example of socketIO (https://socket.io/get-started/) I wrote a basic test to check if it connects properly, but always fails

  test('Autoconnect to socket io', () async {
    IO.Socket socket = IO.io('http://192.168.1.11:3000');

    expect(socket.connected, true);
  });

And I'm not using nullsafety

Octonove avatar Apr 28 '21 00:04 Octonove

@0x3C Does this problem still occur? Have you found a solution? If you found it, please share it.

bilalbaz1 avatar May 13 '21 17:05 bilalbaz1

@bilalbaz1, no I did not end up with a resolution to this issue. With my app still in its infancy, I dropped Node.js entirely, and switched to a Dart back end. I was able to use socket.io-dart and socket.io-client-dart together without issue.

Jarrod-Herbert avatar May 13 '21 17:05 Jarrod-Herbert

I had the same issue but i changed my code like this and it started working for some reason.

Socket IO 2.3.0 Flutter 2.2.2 socket_io_client: ^2.0.0-beta.3-nullsafety.0

void connectToServer() {
    try {
      // Configure socket transports must be sepecified
      IO.Socket socket = IO.io('http://localhost:2000', <String, dynamic>{
        'transports': ['websocket'],
        'autoConnect': false,
      });

      // Connect to websocket
      socket.connect();

      // Handle socket events
      socket.on('connect', (_) => print('connect: ${socket.id}'));
      socket.on('disconnect', (_) => print('disconnect'));
      socket.on('fromServer', (_) => print(_));
    } catch (e) {
      print(e.toString());
    }
  }

janithcooray avatar Jun 14 '21 14:06 janithcooray

I had the same issue but i changed my code like this and it started working for some reason.

Socket IO 2.3.0 Flutter 2.2.2 socket_io_client: ^2.0.0-beta.3-nullsafety.0

void connectToServer() {
    try {
      // Configure socket transports must be sepecified
      IO.Socket socket = IO.io('http://localhost:2000', <String, dynamic>{
        'transports': ['websocket'],
        'autoConnect': false,
      });

      // Connect to websocket
      socket.connect();

      // Handle socket events
      socket.on('connect', (_) => print('connect: ${socket.id}'));
      socket.on('disconnect', (_) => print('disconnect'));
      socket.on('fromServer', (_) => print(_));
    } catch (e) {
      print(e.toString());
    }
  }

I don't know how you reached that conclusion mate, but it does work and I'm really happy that I gave one more try searching solution for this problem before switching to a dart server.

Devanshusisodiya avatar Jun 19 '21 19:06 Devanshusisodiya

I had the same issue but i changed my code like this and it started working for some reason.

Socket IO 2.3.0 Flutter 2.2.2 socket_io_client: ^2.0.0-beta.3-nullsafety.0

void connectToServer() {
    try {
      // Configure socket transports must be sepecified
      IO.Socket socket = IO.io('http://localhost:2000', <String, dynamic>{
        'transports': ['websocket'],
        'autoConnect': false,
      });

      // Connect to websocket
      socket.connect();

      // Handle socket events
      socket.on('connect', (_) => print('connect: ${socket.id}'));
      socket.on('disconnect', (_) => print('disconnect'));
      socket.on('fromServer', (_) => print(_));
    } catch (e) {
      print(e.toString());
    }
  }

I don't know how you reached that conclusion mate, but it does work and I'm really happy that I gave one more try searching solution for this problem before switching to a dart server.

so this means the futter client is not updated. better wait for the 3.0 supported client.

janithcooray avatar Jun 20 '21 11:06 janithcooray

Implementing the beta version 2.* Fixed my issue as my server was running on version 4.*

tiagocdr avatar Nov 29 '21 21:11 tiagocdr