nodejs - socket.io
kevin.Zhu 发布于:2013-1-16 14:28 分类:Nodejs 有 13 人浏览,获得评论 0 条
说明: 有两部分构成 、 socketio ,socketio-client
安装:
npm install --save socket.io
例子:
服务端: index.js
var app = require('express')(); //创建应用实例
var http = require('http').Server(app); //创建http服务器
var io = require('socket.io')(http); //socket服务
app.get('/', function(req, res){
res.sendfile('index.html'); //向客户端发送index.html
});
io.on('connection', function(socket){ //成功连接、 创建了socket连接
console.log(socket.id); //当前socket的连接id (唯一)
console.log('a user connected');
socket.on('disconnect', function(){ //socket连接断开触发
console.log('user disconnected');
});
socket.on('chat message', function(msg){ //"chat message"事件
console.log('message: ' + msg);
});
socket.on('chat message', function(msg){ //"chat message" 事件
socket.emit('chat message', msg); //socket向本连接的用户发送一个"chat message"事件 、并且发送msg消息
socket.broadcast.emit('chat message',msg); //向所有连接的用户广播 “chat message" 事件 、 并且发送 msg
});
});
//创建监听 3000
http.listen(3000, function(){
console.log('listening on *:3000');
});
客户端浏览器html:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script> <!-- 引入socket.io 客户端 -->
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io(); //创建socket连接、 没有指定参数 默认为连接当前服务器
$('form').submit(function(){ //表单提交事件
socket.emit('chat message', $('#m').val()); //提交一个"chat message" 到服务器端 、并且发送msg消息
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){ //监听"chat message" 事件 、
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
运行:
服务端: node index.js
################################ 更多例子 #######################
http://www.nodejs.net/a/20130107/220149.html # 通俗例子、
server :
// note, io(<port>) will create a http server for you
var io = require('socket.io')(80);
io.on('connection', function (socket) {
io.emit('this', { will: 'be received by everyone'});
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});
socket.on('disconnect', function () {
io.emit('user disconnected');
});
});