Amr Ibrahim
Amr Ibrahim

Reputation: 2234

Nodejs Socket.io Express failed to handshake after calling HTTP API

I am using SocketIo with Nodejs, Express server and MongoDB, I followed the documentation . it works fine when connecting multiple clients they can send messages to each other without any problem . when I made an Http request, I cannot connect any new clients and get this error.

socket.io.js:7370 WebSocket connection to 'ws://localhost:28232/socket.io/?userId=userAmr&EIO=3&transport=websocket&sid=wNTTgrUD-PSeNaIcAAAF' failed: Error during WebSocket handshake: Unexpected response code: 400

the other connected users before the Http request can continue sending messages without any problem.

I debugged the Socket library and found the client socket request go to connect function then fire errorCode:1

This this my code

/**
 * Create Express server.
 */
const app = express();


// API endpoint
app.get('/api/test',(req,res)=>{
    res.status(200).send({test:"test"});
});



/**
 * Init socket
 */
// the following line not working too
// const server = require('http').createServer(app);
const server = require('http').Server(app);
const io = require('socket.io')(server);


io.on('connection', (socket) => {

        // emit message to group
        socket.on('emitMessage', (data) => {
                io.emit('emitMessage', data);
        });
});

The Client side code

import { Injectable } from '@angular/core';
import * as io from "socket.io-client/dist/socket.io.js"
import { BehaviorSubject } from 'rxjs';


@Injectable()
export class AppSocketService {
  private url = 'http://localhost:28232';
  private socket;

  constructor() {

  }

  connect(){
    
    this.socket = io(this.url,{
      query:{userid:"123"},
      forceNew:true,
      'force new connection': true,
      autoConnect: true,
      reconnectionDelay: 1000,
      timeout: 100000,
      reconnectionDelayMax: 5000,});

    this.socket.on('connect', () => {
      console.log("connect",{"socketId":this.socket.id});
      this.startListening();
    });


 
  }





  startListening(){
      this.socket.on('emitMessage', (data) => {
        console.log(data);
      });
  }
  

  emitMessage(message){
    this.socket.emit('emitMessage', {message});
  }








}

Client version:"socket.io-client": "^1.7.3"

Server version: "socket.io": "^1.7.3"

Upvotes: 1

Views: 1847

Answers (1)

Amr Ibrahim
Amr Ibrahim

Reputation: 2234

i found the problem, the package express-status-monitor making this wrong behavior .

try to remove it, and it will work perfectly

 // comment these lines, as they making the issue
 // const expressStatusMonitor = require('express-status-monitor'); 
 // app.use(expressStatusMonitor());

The final code:

let app = require('express')();

// these two lines were making the problem, please comment them. if you want to reproduce the problem enable them again 
// const expressStatusMonitor = require('express-status-monitor');
// app.use(expressStatusMonitor());

let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});



app.get('/api/v0/availabilities',(req,res)=>{
    res.status(200).send({test:"test"});
});


io.on('connection', (socket) => {

    // emit message to group
    socket.on('emitMessage', (data) => {
        io.emit('emitMessage', data);
    });
});

http.listen(port, function(){
    console.log('listening on *:' + port);
});

Upvotes: 4

Related Questions