WebSocket-Node是对WebSocket协议实现的Node.js扩展。
服务器端示例代码:
#!/usr/bi/evodevarWebSocketServer=require('websocket').server;varhttp=require('http');varserver=http.createServer(fuctio(request,respose){cosole.log((ewDate())+'Receivedrequestfor'+request.url);respose.writeHead(404);respose.ed();});server.liste(8080,fuctio(){cosole.log((ewDate())+'Serverislisteigoport8080');});wsServer=ewWebSocketServer({httpServer:server,//YoushouldotuseautoAcceptCoectiosforproductio//applicatios,asitdefeatsallstadardcross-origiprotectio//facilitiesbuiltitotheprotocoladthebrowser.Youshould//*always*verifythecoectio'sorigiaddecidewhetherorot//toacceptit.autoAcceptCoectios:false});fuctioorigiIsAllowed(origi){//putlogicheretodetectwhetherthespecifiedorigiisallowed.returtrue;}wsServer.o('request',fuctio(request){if(!origiIsAllowed(request.origi)){//Makesureweolyacceptrequestsfromaallowedorigirequest.reject();cosole.log((ewDate())+'Coectiofromorigi'+request.origi+'rejected.');retur;}varcoectio=request.accept('echo-protocol',request.origi);cosole.log((ewDate())+'Coectioaccepted.');coectio.o('message',fuctio(message){if(message.type==='utf8'){cosole.log('ReceivedMessage:'+message.utf8Data);coectio.sedUTF(message.utf8Data);}elseif(message.type==='biary'){cosole.log('ReceivedBiaryMessageof'+message.biaryData.legth+'bytes');coectio.sedBytes(message.biaryData);}});coectio.o('close',fuctio(reasoCode,descriptio){cosole.log((ewDate())+'Peer'+coectio.remoteAddress+'discoected.');});});
评论