简体   繁体   中英

Not able to connect socket.io in nodejs

Hi I am trying to setup a connection with socket.IO but not able to do so. At present I am not getting any error but the connection is not taking place.Please find below the relevant details:

app.js

const express = require('express');
require('./db/mongoose');
const functions = require("firebase-functions");
var bodyParser = require('body-parser');
const app = express();
const http = require('http').createServer(app);
var io = require('socket.io');
socket = io(http, {cors: {
  origin: "http://localhost",
  methods: ["GET", "POST"]
}
});
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');

app.use(cors()); 

const portCheck = process.env.PORT || 3001

socket.on('connection', function (socket) {
  console.log('connected to socket');
  socket.emit('greeting-from-server', {
      greeting: 'Hello Client'
  });
});


 app.listen(portCheck, ()=> {
            console.log('Server Listening to port:' + portCheck);
 })

Changes should done for your code as follows:

  1. Change app listen with server listen
  2. wrap socket.on(//...) with io.on(//...)
  3. replace this lines
const app = express();const http = 
require('http').createServer(app);

with

var server = require('http').Server(app);
var io = require('socket.io')(server);

After the changes code is like follows.

const express = require('express');
require('./db/mongoose');
const functions = require("firebase-functions");
var bodyParser = require('body-parser');
const app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
socket = io(http, {cors: {
  origin: "http://localhost",
  methods: ["GET", "POST"]
}
});
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');

app.use(cors()); 

const portCheck = process.env.PORT || 3001
server.listen(portCheck, ()=> {
            console.log('Server Listening to port:' + portCheck);
 })

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

  socket.on('connection', function (socket) {
  console.log('connected to socket');
  socket.emit('greeting-from-server', {
      greeting: 'Hello Client'
       });
    });
});

follow more information through this link. https://socket.io/get-started/chat .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM