我知道这个问题很多次,但我没有得到任何对我有用的答案。所以我发布了它。
我有两个文件,一个是test.html,即。
<script src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(function () {
// if user is running mozilla then use it's built-in WebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://localhost:8080/');
connection.onopen = function () {
// connection is opened and ready to use
alert('connection Open');
};
connection.onerror = function (error) {
// an error occurred when sending/receiving data
alert('Error');
};
connection.onmessage = function (message) {
alert('Message');
};
});
</script>
一个nodejs文件是
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received 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
});
function originIsAllowed(origin) {
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
console.log(message);
connection.sendBytes(message);
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
当我尝试使用我的html文件连接web-socket时,它给我的错误是&#34; Firefox无法在ws:// localhost:8080 /&#34;与服务器建立连接。
提前感谢您的帮助。