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.');});});
评论