Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unknown0perator/c689369601031acbb7e9cfda97fc4935 to your computer and use it in GitHub Desktop.
Save unknown0perator/c689369601031acbb7e9cfda97fc4935 to your computer and use it in GitHub Desktop.
Simple Socket.IO (one-file example) [StackOverflow Answer]
//------------------------- (index.html) : this is just to test / better make a file : ------------------
const HTML_index = '<html><head><script src="/socket.io/socket.io.js"></script></head>'+
'<body><button onclick="return chatTest()">EMISSION TEST</button><div id="chatLog"></div><script>'+
'var socket = io();'+
'socket.connect("localhost:3000");'+
'socket.on("chat message",function(msg){'+
' var this_msg = msg + "<br/>"; document.getElementById("chatLog").innerHTML += this_msg ;'+
'});'+
'function chatTest(){socket.emit("chat message","testing socket emission : success");}'+
'</script></body></html>';
//-------------------------------------------------------------------------------------------------------
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'));
// propagate the message to all the clients :
socket.on('chat message', function(msg){
console.log('[socket]',':chat message:',msg);
io.emit('chat message',msg);
});
});
server.listen(PORT,function(){console.log("[SERVER] listening @ port:",PORT);});
//GET Routes
//no need for this in this 'one-file' example
/*
app.use(express.static(__dirname + '/public'))
app.get('/',function(req,res){res.sendFile(INDEX);});
*/
// (this is only for this one-file example) :
app.get('/',function(req,res){res.send(HTML_index);}); //serving the in-memory index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment