3

I want to make a chat application using oop architecture and javascript ES6 syntax. I don't know how to initialize socket.io. I did not find any help.

Here is my code.

import express from 'express';
import http from 'http';
import config from 'config';
import SocketIO from 'socket.io'

const app = express();
const port = config.PORT;
app.set('port', port);
const server = http.createServer(app);
var io = SocketIO(server);
io.on('connection', socket => {
    console.log("Socket connected");
    
});

server.listen(port, () => console.log(`API running on localhost:${port}`));

I am trying to connect socket using socket-client-tool, it shows connection timeout.

8
  • 1
    I am trying to connect through socket-client-tool amritb.github.io/socketio-client-tool Commented Jan 14, 2021 at 14:53
  • where/how are you hosting your server? maybe you're not listening to the port your cloud provider expects you to listen on? Commented Jan 14, 2021 at 14:59
  • i am currently on local host and also listening port.but nothing Commented Jan 14, 2021 at 15:01
  • I also tried it with require instead of import. Its working with require Commented Jan 14, 2021 at 15:02
  • wait, how can you use amritb.github.io/socketio-client-tool then? are you using some tunneling tool? what exactly are you passing as "server url" in the socket-client-tool? Commented Jan 14, 2021 at 15:02

5 Answers 5

7

Using import socketIo from 'socket.io'; did not work in my case.

I used the following method to solve this issue and to connect the socket to my already existing node express server on port 5000.

import cors from 'cors';
import { createServer } from 'http';
import { Server } from 'socket.io'; //replaces (import socketIo from 'socket.io')

const httpServer = createServer(app);
const io = new Server(httpServer, { cors: { origin: '*' } });


io.on('connection', (socket) => {
  console.log('Connection established');
 
getApiAndEmit(socket);
  socket.on('disconnect', () => {
    console.log('Disconnected');
  });
});


const getApiAndEmit = (socket) => {
  const response = 'response you need';
  socket.emit('FromAPI', response);
};

app.set('port', process.env.PORT || 5000);

httpServer.listen(app.get('port'), function () {
  var port = httpServer.address().port;
  console.log('Running on : ', port);
});

And in the client, I connected as follows:

import React,{ useState, useEffect } from 'react';
import socketIOClient from 'socket.io-client';

const ENDPOINT = 'http://127.0.0.1:5000'; //endpoint port 5000

const MyComponent = () => {

  const [response, setResponse] = useState('');

  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    console.log(socket);
    console.log(ENDPOINT);
    socket.on('FromAPI', (data) => {
      setResponse(data);
    });

  }, []);

     return <p>{response}</p>

}

export default MyComponent;
Sign up to request clarification or add additional context in comments.

Comments

1

I'm using it in a small project with React on the front, the server code looks like this

import bodyParser from 'body-parser';
import express from 'express';
import http from 'http';
import socketIo from 'socket.io';
import session from 'express-session'

var app = express();
const server = http.createServer(app)
   

// hook up session for express routes
const sessionMiddleware = session({
    // genid: req => uuidv4(),
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: {}
})

// hook up the session for socket.io connections
io.use((socket, next) => sessionMiddleware(socket.request, socket.request.res || {}, next));
app.use(sessionMiddleware)


io.origins('*:*')
io.on("connection", (socket) => {
    // socket.handshake.headers
    console.log(`socket.io connected: ${socket.id}`);    
    
    const { roomId } = socket.handshake.query;
    socket.join(roomId);
    
    // Leave the room if the user closes the socket
    socket.on("disconnect", () => {
        console.log(`Client ${socket.id} diconnected`);
        socket.leave(roomId);
    });
});
app.use((req, res, next) => {
    req.io = io
    next()
})

app.set('port', (process.env.PORT || 4000));

server.listen(app.get('port'), function () {
    var port = server.address().port;
    console.log("App now running on port", port);
});

Comments

1

For ES6 import statement

Without http . No need to create server with http.

I'm using it with Express + NodeJs backend only and testing it with a website socket io tester , the server.js code looks like this. just paste your http://localhost:8080 and emit or listen to events. socket.io version 2.5.0 is used

import express from 'express';
import SocketIO from 'socket.io';
let app = express();

let port = process.env.PORT || 8080;
let server = app.listen(port, () => {
    console.log('Listening on PORT :' + port);
});

let io = new SocketIO(server);

io.on('connection', (socket) =>
    {
    console.log("on connection",socket.id,);
    socket.on('ding', (ding) => {
        console.log(ding);
      socket.emit("update_user",{key:"value"});

    });

    socket.on('disconnect', () => {

        console.log("disconnected");
    });

    socket.on('userChat', (data) => {

        console.log(data);
    });
}
);

for socket.io >=4.x use this syntax below

import { Server } from "socket.io";
const io = new Server(server);

Comments

0

For ES6 and expressJs use the following format

const app = express();
const PORT = 8000;

const httpServer = app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});
const io = new Server(httpServer); // add after creating the http server

Comments

-2

I have tried the suggested starter code block from the official socket.io documentation (see below) and it works on my end

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

app.get('/', (req, res) => {
  res.send('<h1>Hello world</h1>');
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.