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

使用的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模块里面拷贝下来的)

[javascript]  view plain  copy
  1. #!/usr/bin/env node  
  2. var WebSocketServer = require('websocket').server;  
  3. var http = require('http');  
  4.   
  5. var server = http.createServer(function(request, response) {  
  6.     console.log((new Date()) + ' Received request for ' + request.url);  
  7.     response.writeHead(404);  
  8.     response.end();  
  9. });  
  10. server.listen(8080, function() {  
  11.     console.log((new Date()) + ' Server is listening on port 8080');  
  12. });  
  13.   
  14. wsServer = new WebSocketServer({  
  15.     httpServer: server,  
  16.     // You should not use autoAcceptConnections for production  
  17.     // applications, as it defeats all standard cross-origin protection  
  18.     // facilities built into the protocol and the browser.  You should  
  19.     // *always* verify the connection's origin and decide whether or not  
  20.     // to accept it.  
  21.     autoAcceptConnections: false  
  22. });  
  23.   
  24. function originIsAllowed(origin) {  
  25.   // put logic here to detect whether the specified origin is allowed.  
  26.   return true;  
  27. }  
  28.   
  29. wsServer.on('request'function(request) {  
  30.     if (!originIsAllowed(request.origin)) {  
  31.       // Make sure we only accept requests from an allowed origin  
  32.       request.reject();  
  33.       console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');  
  34.       return;  
  35.     }  
  36.   
  37.     var connection = request.accept('echo-protocol', request.origin);  
  38.     console.log((new Date()) + ' Connection accepted.');  
  39.     connection.on('message'function(message) {  
  40.         if (message.type === 'utf8') {  
  41.             console.log('Received Message: ' + message.utf8Data);  
  42.             connection.sendUTF(message.utf8Data);  
  43.         }  
  44.         else if (message.type === 'binary') {  
  45.             console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');  
  46.             connection.sendBytes(message.binaryData);  
  47.         }  
  48.     });  
  49.     connection.on('close'function(reasonCode, description) {  
  50.         console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');  
  51.     });  
  52. });  

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

node ws.js

结果如图

使用chrome浏览器测试

新建一个html文件

[html]  view plain  copy
  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>Document</title>  
  6. </head>  
  7. <body>  
  8.     <button type="button" id="start" onclick="start()">start</button>  
  9.     <script>  
  10.     function start(){  
  11.         var client = new WebSocket('ws://localhost:8080/', 'echo-protocol');  
  12.         client.onerror = function() {  
  13.             console.log('Connection Error');  
  14.         };  
  15.         client.onopen = function() {  
  16.             console.log('WebSocket Client Connected');  
  17.             function sendNumber() {  
  18.                 if (client.readyState === client.OPEN) {  
  19.                     var number = Math.round(Math.random() * 0xFFFFFF);  
  20.                     client.send(number.toString());  
  21.                     setTimeout(sendNumber, 1000);  
  22.                 }  
  23.             }  
  24.             sendNumber();  
  25.         };  
  26.         client.onclose = function() {  
  27.             console.log('echo-protocol Client Closed');  
  28.         };  
  29.         client.onmessage = function(e) {  
  30.             if (typeof e.data === 'string') {  
  31.                 console.log("Received: '" + e.data + "'");  
  32.             }  
  33.         };  
  34.     }  
  35.     </script>  
  36. </body>  
  37. </html>  

猜你喜欢

转载自blog.csdn.net/sinat_18474835/article/details/80004641
今日推荐