0

I have tried many methods to connect socket-io client and server with express but its not working and now i do not know what could be error.

i have tried to clone example available on socket-io website still it does not show any connectivity or any functions do not emmit.

This is server.js and this is my code i have made many changes in it but not working.

var express = require('express');
var app = express();
var path = require('path');
//require socket.io
var http = require('http').createServer(app);
var io = require('socket.io')(http);

//Setup a public path to load files
app.use(express.static('public'))
//app.use(express.static(path.join(__dirname, 'public')));

//Route for index
app.get(('/'),(req,res)=>{
    res.send('index'); 
});

//Socket connection

io.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
      console.log(data);
    });
  });



app.listen(3000,()=>{
    console.log('server running on port 3000');}
);

This is index.html that the server.js is sending i only included the script

    <script src="/socket.io/socket.io.js"></script>
   
   <script>
      var socket = io.connect('http://localhost:3000');
      socket.on('news', function (data) {
        console.log(data);
        socket.emit('my other event', { my: 'data' });
      });
    </script>

I expect it to console log when socket is connected and disconnected and emit the functions normally.
Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130

1 Answers1

0

Hello Here is your working example of socket.io

In Your server code

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

//Listen on port 3000
server = app.listen(3000, () => {
    console.log('server running on port 3000');
})

//socket.io instantiation
const io = require("socket.io")(server)


//listen on every connection
io.on('connection', (socket) => {
    console.log('New user connected')

    socket.emit('news', { hello: 'world' });
})

Here is HTML code

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost:3000');
    socket.on('news', function (data) {
        console.log(data);
        socket.emit('my other event', { my: 'data' });
    });
</script>
Ankur Patel
  • 478
  • 3
  • 6