Skip to content

Instantly share code, notes, and snippets.

@grifdail
Last active August 29, 2015 13:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grifdail/10123362 to your computer and use it in GitHub Desktop.
Save grifdail/10123362 to your computer and use it in GitHub Desktop.
Everything you need to make realtime connection between peer (perfect for simple multiplayer game with no cheat protection) with socket.io and express in 53 line (plus a chat in the console & a bunny)
<html>
<head>
<title>Open the chat !</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var id, socket = var socket = io.connect();
/*
|\ /|
\|_|/
/. .\
=\_Y_/=
{>o<}
*/
socket.on("new socket id", function(newId) {
id = newId;
});
console.chat = function(message) {
socket.emit("publish",{name:"chat message",arg:message});
}
socket.on("chat message", function(message) {
console.log(message);
});
console.log("use console.chat to chat");
</script>
</body>
</html>
var express = require('express');
var app = express()
var port = 8087;
var http = require('http')
var server = http.createServer(app).listen(port)
var io = require('socket.io').listen(server);
app.use("/",express.static(__dirname + '/'));
io.sockets.on('connection', function (socket) {
socket.on('broadcast', function (data) {
socket.broadcast.emit(data.name, data.arg);
});
socket.on('publish', function (data) {
io.sockets.emit(data.name, data.arg);
});
socket.on('disconnect', function (data) {
io.sockets.emit(socket.id);
});
socket.emit("new socket id",socket.id);
});
console.log("listening on port "+port+".")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment