用socket.io实现WebSocket的一个简单例子用socket.io实现WebSocket的一个简单例子客户端代码:var http re
用socket.io实现WebSocket的一个简单例子
用socket.io实现WebSocket的一个简单例子
客户端代码:
var http= require('http'), io= require('socket.io'), express= require('express');var app = express.createServer(), io = io.listen(app);app.listen(80);io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' });//监听,一旦客户端连接上,即发送数据,第一个参数'new'为数据名,第二个参数既为数据 socket.on('my other event', function (data) {//捕获客户端发送名为'my other event'的数据 console.log(data.my); }); socket.emit('other', { hello: 'other world' });//发送另一个数据 socket.on('evnet1', function (data) {//捕获另外一个数据 console.log(data.my); });});测试结果,客户端可正常显示
引用world
other world
服务器端显示结果:
引用C:\java\Nodejs>node server2.js
info - socket.io started
debug - client authorized
info - handshake authorized 15551970622100878177
debug - setting request GET /socket.io/1/websocket/15551970622100878177
debug - set heartbeat interval for client 15551970622100878177
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"news","args":[{"hello":"world"}]}
debug - websocket writing 5:::{"name":"other","args":[{"hello":"other world"}
]}
debug - emitting heartbeat for client 15551970622100878177
debug - websocket writing 2::
debug - set heartbeat timeout for client 15551970622100878177
debug - got heartbeat packet
debug - cleared heartbeat timeout for client 15551970622100878177
debug - set heartbeat interval for client 15551970622100878177
^C