本地跑一个WebSocketServer. 跑不起来的自己去百度一下喽, npm, 不介绍喽, 百度查怎么安装。
npm install ws
创建app.js文件
"use strict";
var webSocketsServerPort = 8081; // 监听的端口
var webSocketServer = require('websocket').server; // 生成对象
var http = require('http');
var clients = [ ];
// 转换
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/>/g, '>').replace(/"/g, '"');
}
// HTTP server
var server = http.createServer(function(request, response) {
});
server.listen(webSocketsServerPort, function() {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});
// WebSocket server
var wsServer = new webSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
var connection = request.accept(null, request.origin);
var index = clients.push(connection) - 1;
var dataDict = false;
console.log((new Date()) + ' Connection accepted.');
// user sent some message
connection.on('message', function(message) {
if (message.type === 'utf8') { // accept only text
dataDict = JSON.parse(htmlEntities(message.utf8Data));
console.log((new Date()) + ' User is known as: ' + dataDict);
var eventName = dataDict['event'];
var eventID_GET = dataDict['eventID'];
console.log('eventName: ' + eventName + '\n' + 'eventID: ' + eventID_GET);
// 登录事件
if (eventName == 'login') {
connection.sendUTF(JSON.stringify({
event:'loginsuccess',
eventID:eventID_GET,
eventTime:Date.parse(new Date()),
eventStatu:'1',
data:{
userID:'Dylan',
nickName:'WildDylan',
headimg:'http://img2.imgtn.bdimg.com/it/u=4093725959,796807213&fm=21&gp=0.jpg'
}
}));
}
// 消息事件
if (eventName == 'message') {
connection.sendUTF(JSON.stringify({
event:'ackServerEvent',
eventID:eventID_GET,
eventTime:Date.parse(new Date()),
eventStatu:'1',
data:{
}
}));
// 测试回复一条消息
connection.sendUTF(JSON.stringify({
event:'message',
eventID:Date.parse(new Date()),
eventTime:Date.parse(new Date()),
eventStatu:'1',
data:{
userID:'Dylan_test_1',
messageID:Date.parse(new Date()),
messageComm:'qingke',
conversionID:'currentConversionID',
messageDate:Date.parse(new Date()),
messageContent:{
extra:'Message Extra',
pushMessage:'New Message Coming...',
content:Date.parse(new Date()) + '_msg',
},
messageType:'0',
sentStatu:'40',
messageDirection:'1'
}
}));
console.log('re message!');
}
}
});
connection.on('close', function(connection){
console.log((new Date()) + " Peer "
+ connection.remoteAddress + " disconnected.");
});
});
然后 node app.js, 本地的ws服务就会run起来
@WildDylan 2015.11.4
网友评论