WebSocket更新后,解决Sec-WebSocket-Key问题------>方法
发布于 2年前 作者 jacky80 1038 次浏览

哎,0回复的楼主伤不起啊,好吧,简单的把我的渣技术讲一下: 上一帖思路中已经讲过了websocket的限制问题,分享一下我的解决办法:(很详细) 先装模块,npm install WebSocket-Node,如有提示请参照------>思路的内容。 下面是源代码:

var WebSocketServer = require('websocket').server;
var http = require('http');
var clients = [];

var server = http.createServer(function (request, response) {
    console.log(new Date + ' Receive request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function(){
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({httpServer: server, autoAcceptConnections: false});

wsServer.on('request', function(request){
    var connection = request.accept('echo-protocol', request.origin);
    clients.push(connection);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message){
        console.log('Received Message: ' + message.utf8Data);
        var json = JSON.stringify({ type:'message', data: message.utf8Data });
        for(i = 0; i < clients.length; i++){
            clients[i].sendUTF(json);
        }
    });
    connection.on('close', function(reasonCode, description){
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

木有别的功能,只是简单的消息转发的例子,觉得社区的那篇热帖过时了,希望大家不要再走弯路而已,应该是很简单的吧,有什么不明白,不要客气…… 另外,客户端在new 对象的时候要这样: var ws = new WebSocket("ws://localhost:8080", ‘echo-protocol’); 不然会报错的哦~

1 回复

严重感谢LZ啦啦啦~~

回到顶部