Skip to content

Instantly share code, notes, and snippets.

@andy12530
Created October 9, 2012 12:27
Show Gist options
  • Save andy12530/3858512 to your computer and use it in GitHub Desktop.
Save andy12530/3858512 to your computer and use it in GitHub Desktop.
Socket.io SSE Demo 跨浏览器、平台
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
window.onload = function() {
var socketIo = io.connect('http://localhost');
socketIo.on('connection', function(data) {
insertMsg(data);
})
socketIo.on('message', function(data) {
insertMsg(data);
});
function insertMsg(msg) {
var text = document.createTextNode(msg);
var li = document.createElement("li");
li.appendChild(text);
document.getElementById("chat-box").appendChild(li);
}
var send = document.getElementById('send');
send.addEventListener('click', function(event) {
event.preventDefault();
var nick = document.getElementById('nick').value;
var talk = document.getElementById('talk').value;
if(!talk) return false;
var message = nick + " 说 :" + talk;
socketIo.send(message);
document.getElementById('talk').value = "";
}, false);
}
</script>
</head>
<body>
<div id="chat-box" style="bordddder:1px solid #cccccc; height:400px; overflow:scroll;"></div>
昵称:<input type="text" id="nick"/><br/>
内容:<input type="text" id="talk"/><input type="button" id="send" value="发送"/>
</body>
</html>
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs');
app.listen(1333);
function handler(req, res) {
fs.readFile('socketIo.html', function(err, data) {
if (err) {
res.writeHead(500);
return res.end("Error");
}
res.writeHead(200);
res.end(data);
});
}
var clients = [];
io.sockets.on('connection', function (client) {
client.send("Welcome to chat room!");
clients.push(client);
client.on('message', function(data) {
clients.forEach(function(cli) {
cli.send(data);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment