I know this question ask to many times but I didn't get any answer which work for me. So I am posting it.
I have two file one is test.html which is .
<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>
And one nodejs file which is
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.');
});
});
While I am trying to connect with web-socket with my html file its give me error which is "Firefox can't establish a connection to the server at ws://localhost:8080/"
Thanks in advance for help.
It should be able to find and connect to the server but the server will reject your request and shutdown because of request.accept('echo-protocol', request.origin)
in your server file.
Check the log of you nodejs command prompt.
To fix this just modify
var connection = new WebSocket('ws://localhost:8080/');
to
var connection = new WebSocket('ws://localhost:8080/', 'echo-protocol');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.