0

I want to use the emit event in the express router, so I am trying to pass a global.io.

But the problem is , even if I add this code

io.emit('join','Tudis')

in the server.js , I can't see any response output,

(I think there should be 'someone joined :Tudis' right after compiling?) please enlighten me , thank you so much.

-----the code of server.js---------

const express = require('express')
const socketio=require('socket.io')
const http=require('http')

const serverPORT=5000

const app = express();
const server = http.createServer(app)
const io=socketio(server)

io.on('connection',(socket)=>{   
  socket.on('join',(name)=>{
    console.log('someone joined :' + name)
  }) 
})

global.io=io
const router=require('./router')
app.use(router)

io.emit('join','Tudis')

server.listen(serverPORT,
  ()=> console.log('server is up at : '+serverPORT)
  )
Tudis Lei
  • 31
  • 1
  • 4
  • Hi, I think you need a client also connected to the socket that your server is attached to, and your client should emit this message `'join'` – Biswa Soren Jul 21 '20 at 06:12
  • I personally recommend you to use this [socket.io client](https://amritb.github.io/socketio-client-tool) tool, connect this to your server and send a message '`join'` – Biswa Soren Jul 21 '20 at 06:14
  • At the time you do `io.emit('join', 'Tudis')`, your server has just started and there are no connected clients. So, that message doesn't get sent to anyone because there's no one connected to send it to. If you put that inside the `socket.on('join', ...)` handler, then you will get that message. – jfriend00 Jul 21 '20 at 06:17

1 Answers1

0

I found my answer.... thank you all !! I am really so happy !!

Node.js client for a socket.io server

//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {reconnect: true});
socket.emit('CH01', 'me', 'test msg');

after such a long way of studying...feeling pretty exhausted but I think I can finally start to build something XD

Thank you!!!!!

(by the way before I choose this way, I was actually using the puppeteer to visit the website to send the emit ..

lol it 'worked' though)

Tudis Lei
  • 31
  • 1
  • 4