Reputation: 41
Hey there i'm trying to send message to everyone connected to the server that a new user is connected except the new user connect so i'm using socket.broadcast.emit() but it doesn't fire up in browser console
my code :
const path = require('path')
const http = require('http')
const express = require('express')
const socketio = require('socket.io')
const app = express()
const server = http.createServer(app)
const io = socketio(server)
const port = process.env.PORT || 3000
const publicDirectoryPath = path.join(__dirname,'../public')
app.use(express.static(publicDirectoryPath))
io.on('connection',(socket)=>{
console.log('New web socket connection')
socket.emit('welcome',"Welcome !")
socket.broadcast.emit('message','A new user has joined !')
socket.on('sendMessage',(message)=>{
io.emit('messageSent',message)
})
})
server.listen(port,()=>{
console.log('Server is up on 3000')
})
Upvotes: 2
Views: 1882
Reputation: 11770
You can send to everyone (including yourself) with:
io.emit(...)
Or to everyone else (but not yourself - i.e. not socket
) with:
socket.broadcast.emit(...)
Upvotes: 3