Unknown connections socket.io

117 Views Asked by At

I'm playing around with React+Socket.io by creating a simple application with real-time value update with +/- buttons and I came across several problems.

  1. I just found out that my server has new connections with differend socket IDs every few seconds, but the react app isn't running.
  2. Server doesn't see emmiting from the react side.

When I click on the increment or decrement button nothing happens. The server doesn't display a message that it has received something, but at the same time it doesn't display any errors.


server.js

const app = require('express')()
const http = require('http').Server(app)
const io = require('socket.io')(http)

io.on('connection', socket => {
    console.log(`connected: ${socket.id}`)
    socket.on('new-value', value => {
        console.log(`new value: ${value}`);
        io.emit('new-value', value);
    })
})

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

App.js

import { useState, useEffect } from 'react';
import './App.css';

import io from 'socket.io-client';
const socket = io('localhost:4000');

function App() {
    const [value, setValue] = useState(0);

    useEffect(() => {
        socket.on('new-value', val => {
            setValue(val);
        })
    }, []);

    const dec = () => socket.emit('new-value', value - 1);
    const inc = () => socket.emit('new-value', value + 1);

    return (
        <div className="App">
            <div id="wrap">
                <button type="button" onClick={dec}>-</button>
                <span className="num-span">{value}</span>
                <button type="button" onClick={inc}>+</button>
            </div>
        </div>
    );
}

export default App;

server.js console output

> [email protected] start
> node server.js

listening on port 4000
connected: K-1X0atTHX1lgCWIAAAA
connected: 0Bq4aVquvwF1wIWkAAAB
connected: HbFvaLQEsBjjBMbUAAAC
connected: ldHBhGUo0CwtAlIGAAAD
connected: n7myM1RFNruzXhmgAAAE
connected: WIF96kQarkss29mRAAAF
connected: ieIEKOi-RLdYoN8PAAAG
connected: cUDLIqeJo_6-RzxPAAAH
connected: tixuslvbrnJ1OPK1AAAI
connected: rVVEKDPAIUpaF4FjAAAJ
connected: jepnS4tSo4DW396fAAAK
connected: wlVJ6v6JhNA8m9VdAAAL

I tried to find something on the Internet, but I still have no idea where these connections come from. Am I missing something?

1

There are 1 best solutions below

0
On

The problem was in the socket.io-client version.

I rolled it back to 2.1.1 with npm install [email protected] and now everything works just fine.