使用node.js webSocket 建立客户端与服务端之间的通信示例

需要安装 node.js 通过npm 安装 webSocket包

npm install websocket

 客户端

var WebSocketClient = require('websocket').client;//获取websocketclient模块

var client = new WebSocketClient();//创建客户端对象


 

//连接失败执行

client.on('connectFailed',

function(error){

console.log('Connect Error: ' + error.toString());}

);

 

client.on('connect', function(connection)

{

console.log('WebSocket Client Connected');

 

//连接错误抛出

connection.on('error', function(error) {

console.log("Connection Error: " + error.toString());

});

 

//连接关闭执行

connection.on('close', function() {

console.log('echo-protocol Connection Closed');

});

 

//收到服务器的返回消息

connection.on('message', function(message) {

if (message.type === 'utf8') {

console.log("Received: '" + message.utf8Data + "'");

}

});

function sendNumber()

{

if (connection.connected) //如果连接 连接上了

{

var number = Math.round(Math.random() * 0xFFFFFF);

connection.sendUTF(number.toString());//连接发送数据

setTimeout(sendNumber, 1000);//延时递归调用

}

}

sendNumber();

});

client.connect('ws://localhost:8080/', 'echo-protocol');//连接服务器

服务端 

var WebSocketServer = require('websocket').server;//获取websocketserver模块

var http = require('http');//获取http模块

//建立http服务器对象

var server = http.createServer(function(request, response) {

console.log((new Date()) + ' Received request for ' + request.url);

response.writeHead(404);

response.end();

});

 

//http服务器对象监听端口8080

server.listen(8080, function() {

console.log((new Date()) + ' Server is listening on port 8080');

});

//建立WebSocketServer对象 绑定http服务器对象

wsServer = new WebSocketServer({

httpServer: server,

// You should not use autoAcceptConnections for production

// applications, as it defeats all standard cross-origin protection

// facilities built into the protocol and the browser. You should

// *always* verify the connection's origin and decide whether or not

// to accept it.

autoAcceptConnections: false

});

//验证是否时允许来源的请求

function originIsAllowed(origin) {

// put logic here to detect whether the specified origin is allowed.

return true;

}

 

wsServer.on('request', function(request)

{

if (!originIsAllowed(request.origin)) //不是允许来源的请求 就拒绝连接 确保我们只接受来自允许来源的请求

{

request.reject();

console.log((new Date()) + ' Connection from origin ' + ' rejected.');

return;

}

//同意连接

var connection = request.accept('echo-protocol', request.origin);

console.log((new Date()) + connection.remoteAddress +' Connection accepted.');

//监听这个连接 收到客户端发来的消息执行

connection.on('message', function(message)

{

if (message.type === 'utf8')

{

console.log('Received Message: ' + message.utf8Data);

connection.sendUTF("来自服务器的消息:我收到你的消息了"+connection.remoteAddress+" "+message.utf8Data);

}

else if (message.type === 'binary')

{

console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');

connection.sendBytes(message.binaryData);

}

});

 

//监听的连接关闭时

connection.on('close', function(reasonCode, description)

{

console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');

});

 

});

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值