在REPL中比较容易调试和发现问题, 所以这儿介绍REPL的玩法.

node.js服务端需要安装模块.

    npm install ws

进入node, 开启服务,等待客户端连接. 为了便于以后向客户端发送消息, 把连接后的ws对象赋值给全局变量thisws

node
>
var thisws
var Wss = require('./ws').Server

var wss = new Wss({port: 3888})
wss.on('connection', function(ws){
    thisws = ws
    console.log('connected.')
    ws.on('message', function(message){
        console.log("msg: ",message)
    })
})

chrome 打开console,进行连接和监听服务器消息

s = new WebSocket('ws://localhost:3888')
s.onmessage = function(e){console.log(e.data)}

好啦!, 在chrome中send消息可以在node那边收到, 在node中send消息也可以在chrome中收到了
先从chrome中send

s.send('我是chrome') // 在node中将看到这条消息.

再从node中send

thisws.send('我是node服务器') //在chrome中将看到这条消息.

当然,除了chrome自带的WebSocket客户端, 在node中ws也提供客户端, 另外,socket.io也是另一种websocket客户端和服务器的提供者.

  • 总结
    浏览器客户端监听和发送
onclose = function(e){}
onmessage = function(e){}
onopen = function(){}
onerror = function(){}

send(string)
close()

node ws服务端监听和发送

wss.on('connection',function(ws){})
wss.on('error', function(err){})
wss.on('header',function(array){})
wss.on('listening',function(){})

ws.on('message',function(message_string,flags){})
ws.on('close',function(code, reason){})
ws.on('error',function(err){})
ws.on('open',function(){})

ws.onclose = function(e){}
ws.onerror = function(e){}
ws.onmessage = function(e){}
ws.onopen = function(e){}
ws.readyState

ws.send(message_string, function(error){})
ws.close(code, reason)

// 所有客户端列表
wss.clients
wss.close(function(){})

参考文章: WebSocket and Socket.IO
node ws API

标签: none 阅读量: 997

添加新评论