Created
December 26, 2013 13:31
-
-
Save baniol/8133888 to your computer and use it in GitHub Desktop.
basic socket server, nodejs, socket.io
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
var express = require('express'); | |
var app = express(); | |
var server = require('http').createServer(app); | |
var io = require('socket.io').listen(server); | |
app.use(express.static(__dirname + '/')); | |
server.listen(8000); | |
app.get('/', function (req, res) { | |
res.sendfile(__dirname + '/index.html'); | |
}); | |
io.sockets.on('connection', function (socket) { | |
socket.emit('news', { hello: 'world' }); | |
socket.on('messages', function (data) { | |
console.log(data); | |
}); | |
socket.on('join', function (data) { | |
var message = 'Username ' + data + ' joined'; | |
console.log(message); | |
socket.broadcast.emit('joined', message); | |
}); | |
}); |
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="/jquery.js"></script> | |
<script src="/socket.io/socket.io.js"></script> | |
</head> | |
<body> | |
<div id="status"></div> | |
<div id="infos"></div> | |
<script> | |
var socket = io.connect('http://localhost:8000'); | |
socket.on('connect', function (data) { | |
$('#status').text('connected'); | |
var nickname = prompt('What is your nickname?'); | |
if (nickname) { | |
socket.emit('join', nickname); | |
} | |
}); | |
socket.on('joined', function (data) { | |
$('#infos').text(data); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment