Skip to content

Instantly share code, notes, and snippets.

@raghavgarg1257
Last active December 2, 2020 08:49
Show Gist options
  • Save raghavgarg1257/8a5af8aaa447b24e345bc20ddea98ba1 to your computer and use it in GitHub Desktop.
Save raghavgarg1257/8a5af8aaa447b24e345bc20ddea98ba1 to your computer and use it in GitHub Desktop.
simple example of socket.io
// require our dependencies
import express from "express";
import socketCon from "./app/socket.js";
// initializing server requirments
const port = process.env.PORT || 3000;
const app = express();
// start the server
const server = app.listen(port, function() {
console.log('app started at ' + port);
});
// set static files (css and images, etc) location
app.use(express.static(__dirname + '/public'));
// socket connection
let io = socketCon(server);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- html element -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
$(function() {
let socket = io();
socket.emit('notification');
socket.on('news', data => {
console.log(`hello - ${data}`);
});
});
</script>
</body>
</html>
import socketIO from "socket.io";
module.exports = server => { // send the server instance as an argument to get socket instance
let io = socketIO(server);
io.on('connection', socket => {
socket.on('notification', () => {
socket.emit('news', { hello: 'world' } );
});
});
// return the instanc of io
return io;
}
@raghavgarg1257
Copy link
Author

raghavgarg1257 commented Dec 2, 2020

@saif5017, are you getting any error? if yes please share the stack trace.

please share your code then I might be able to help you.

this stackoverflow thread might be of some help for you.

@unverifiedchaos
Copy link

    socket.on('joinRoom', ({username, room})=>{

        const user=userJoin(socket.id, username, room)

        socket.join(user.room)

        //welcome the user
        socket.emit('message', formatMessage(botName, 'welcome to chatCord'))

        //notify everyone except user, when a user connects
        socket.broadcast.to(user.room).emit('message', formatMessage(botName, `${user.username} has connected`))
    })

the problem im facing here right now is that socket.emit and socket.boradcast .emit aren't working at all i tried adding a console.log to it to check and it doesn't work either

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment