服务器端:
var app = require('express')();
var http = require('http').Server(app);
var io = require('
socket.io')(http);
app.get('/chat/:route_name', function(req, res){
res.sendfile('index.html');
});
app.get('/client.js', function(req, res){
res.sendfile('client.js');
});
io.on('connection', function(socket){
socket.room_name = socket.room_name || "room1";
console.log("connected");
console.log(socket.room_name);
socket.on("chat message", function(msg){
io.to(socket.room_name).emit('chat message', msg);
});
socket.on("change room", function(room_name) {
socket.room_name = room_name;
socket.join(socket.room_name);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
网页端:
var Once = function(func) {
var status = true;
return function() {
if (status) {
status = false;
func();
}
};
};
var Main = function() {
var room_name = document.location.pathname.split("/").pop();
var socket = io();
socket.emit('change room', room_name);
var $ = function (query) {
return document.querySelector(query);
};
var user_name = "User" + parseInt(Math.random() * 1000000);
$('form').onsubmit = function(){
socket.emit('chat message', {content: $('#m').value, user: user_name});
$('#m').value = "";
return false;
};
socket.on("chat message", function(msg) {
console.log(msg);
var msg_node = document.createElement("li");
msg_node.innerHTML = msg.user + ": " + msg.content;
$('#messages').appendChild(msg_node);
});
}
document.onreadystatechange = Once(Main);