WebSocket-Node开源项目

我要开发同款
匿名用户2013年11月21日
90阅读
开发技术JavaScript
所属分类Node.js扩展、Web应用开发、Node.js 扩展
授权协议Apache

作品详情

WebSocket-Node是对WebSocket协议实现的Node.js扩展。

服务器端示例代码:

#!/usr/bin/envnodevarWebSocketServer=require('websocket').server;varhttp=require('http');varserver=http.createServer(function(request,response){console.log((newDate())+'Receivedrequestfor'+request.url);response.writeHead(404);response.end();});server.listen(8080,function(){console.log((newDate())+'Serverislisteningonport8080');});wsServer=newWebSocketServer({httpServer:server,//YoushouldnotuseautoAcceptConnectionsforproduction//applications,asitdefeatsallstandardcross-originprotection//facilitiesbuiltintotheprotocolandthebrowser.Youshould//*always*verifytheconnection'soriginanddecidewhetherornot//toacceptit.autoAcceptConnections:false});functionoriginIsAllowed(origin){//putlogicheretodetectwhetherthespecifiedoriginisallowed.returntrue;}wsServer.on('request',function(request){if(!originIsAllowed(request.origin)){//Makesureweonlyacceptrequestsfromanallowedoriginrequest.reject();console.log((newDate())+'Connectionfromorigin'+request.origin+'rejected.');return;}varconnection=request.accept('echo-protocol',request.origin);console.log((newDate())+'Connectionaccepted.');connection.on('message',function(message){if(message.type==='utf8'){console.log('ReceivedMessage:'+message.utf8Data);connection.sendUTF(message.utf8Data);}elseif(message.type==='binary'){console.log('ReceivedBinaryMessageof'+message.binaryData.length+'bytes');connection.sendBytes(message.binaryData);}});connection.on('close',function(reasonCode,description){console.log((newDate())+'Peer'+connection.remoteAddress+'disconnected.');});});
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论