Skip to content

Instantly share code, notes, and snippets.

@andy12530
Created October 8, 2012 13:32
Show Gist options
  • Save andy12530/3852563 to your computer and use it in GitHub Desktop.
Save andy12530/3852563 to your computer and use it in GitHub Desktop.
webSocket信息推送
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
window.onload = function() {
var socket = new WebSocket("ws://" + location.host + "/");
socket.onmessage = function(event) {
var msg = event.data;
var node = document.createTextNode(msg);
var li = document.createElement("li");
li.appendChild(node);
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;
console.log(message);
socket.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 http = require('http');
var ws = require('websocket-server');
var clientUI = require('fs').readFileSync('chat.html');
var httpServer = new http.Server();
httpServer.on('request', function(req, res) {
if(req.url === '/') {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.write(clientUI);
res.end();
} else {
res.writeHead(404);
res.end('Not Found!');
}
});
var wsServer = ws.createServer({server: httpServer});
wsServer.on('connection', function(socket) {
socket.send('Welcome to the chat room!');
socket.on('message', function(msg) {
wsServer.broadcast(msg);
});
});
wsServer.listen(1333);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment