windows下使用WebSocket-Node搭建WebSocket服务器

来源:互联网 发布:梦龙网络计划2016 编辑:程序博客网 时间:2024/05/21 07:03

使用的WebSocket-Node模块搭建.
先谢谢那些牛人分享的代码.

第一步:安装好node.js和npm
这个就不赘述了.
在dos命令下测试


第二步:安装WebSocket-Node模块

Node.js command prompt输入命令

npm install websocket

记住,不要全局安装,不然后续调用模块的时候会报类似的Error: Cannot find module 'websocket'错.

第三步:windows下安装Microsoft Visual C++和Python 2.7

(windows下面才需要安装..)一般情况下windows下都会安装有Microsoft Visual C++,所以我们需要继续安装Python 2.7.10下载

第四步:测试WebSocket服务器

创建ws.js文件
输入代码(直接从WebSocket-Node模块里面拷贝下来的)

#!/usr/bin/env nodevar WebSocketServer = require('websocket').server;var http = require('http');var server = http.createServer(function(request, response) {    console.log((new Date()) + ' Received request for ' + request.url);    response.writeHead(404);    response.end();});server.listen(8080, function() {    console.log((new Date()) + ' Server is listening on port 8080');});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)) {      // Make sure we only accept requests from an allowed origin      request.reject();      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');      return;    }    var connection = request.accept('echo-protocol', request.origin);    console.log((new Date()) + ' Connection accepted.');    connection.on('message', function(message) {        if (message.type === 'utf8') {            console.log('Received Message: ' + message.utf8Data);            connection.sendUTF(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.');    });});

Node.js command promp命令cd到你创建的js文件所在目录下面.执行

node ws.js

结果如图

使用chrome浏览器测试

新建一个html文件

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title></head><body>    <button type="button" id="start" onclick="start()">start</button>    <script>    function start(){        var client = new WebSocket('ws://localhost:8080/', 'echo-protocol');        client.onerror = function() {            console.log('Connection Error');        };        client.onopen = function() {            console.log('WebSocket Client Connected');            function sendNumber() {                if (client.readyState === client.OPEN) {                    var number = Math.round(Math.random() * 0xFFFFFF);                    client.send(number.toString());                    setTimeout(sendNumber, 1000);                }            }            sendNumber();        };        client.onclose = function() {            console.log('echo-protocol Client Closed');        };        client.onmessage = function(e) {            if (typeof e.data === 'string') {                console.log("Received: '" + e.data + "'");            }        };    }    </script></body></html>

打开点击start按钮
控制台输出

WebSocket Client Connected 
Received: '6608650'
......

就表示大获成功了.
(后续可以写客户端来测试了,客户端的nodejs代码在那个模块里面也有,我就不贴了.)

本文由 关门咬狗 创作,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。
可自由转载、引用,但需署名作者且注明文章出处。
0 0