Created
August 4, 2017 08:03
-
-
Save unknown0perator/50d6746cfddcb9c5c917b7baa6ae06b2 to your computer and use it in GitHub Desktop.
Simple Socket.IO Working Example (Stack Overflow Answer)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html><head><script src="/socket.io/socket.io.js"></script></head> | |
<body><script> | |
var socket = io(); | |
socket.connect('localhost:3000'); | |
socket.on('chat message',function(msg){ | |
document.write(msg); | |
}); | |
</script></body></html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const socketIO = require('socket.io'); | |
const path = require('path'); | |
const PORT = process.env.PORT || 3000; | |
const INDEX = path.join(__dirname, 'index.html'); | |
// Express & Middleware | |
var app = express(); | |
var bodyParser = require('body-parser'); | |
app.use(bodyParser.json()); | |
// SocketIO | |
var server = require('http').createServer(app); | |
var io = require('socket.io')(server); | |
io.on('connection', function(socket){ | |
console.log('[socket]','client connected'); | |
socket.emit("chat message","[you are now connected]"); | |
socket.on('disconnect', () => console.log('[socket]','client disconnected')); | |
}); | |
server.listen(PORT,function(){console.log("[SERVER] listening @ port:",PORT);}); | |
//GET Routes | |
app.use(express.static(__dirname + '/public')) | |
app.get('/',function(req,res){res.sendFile(INDEX);}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment