博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
nodejs server websocket
阅读量:6041 次
发布时间:2019-06-20

本文共 2056 字,大约阅读时间需要 6 分钟。

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

 

转载于:https://www.cnblogs.com/wblade/p/8570795.html

你可能感兴趣的文章
Nginx SSL+tomcat集群配置SSL,ngnix配置SSL后js/css访问出现404
查看>>
Ubuntu15.05下安装QQ
查看>>
JPA和Hibernate
查看>>
我的友情链接
查看>>
安卓平台的音视频即时通讯
查看>>
linux 搭建packetix *** server
查看>>
Centos7安装kong1.1.2
查看>>
python中的偏函数
查看>>
定义一个线性表
查看>>
第一次登场
查看>>
多条件查询处理
查看>>
我的友情链接
查看>>
Windows Server 2008上创建和管理镜像卷
查看>>
为终端服务用户指定在用户登录时自动启动的程序
查看>>
网络项目
查看>>
Linux服务器---配置samba
查看>>
Neodynamic条码识别控件Barcode Reader SDK for .NET控件详细介绍
查看>>
我的友情链接
查看>>
NFS mount failed, reason given by server: Permission denied 的解决办法
查看>>
rsync in linux
查看>>