I have two files 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 an error which is
Firefox can’t establish a connection to the server at ws://localhost:8080/
The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer's network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web.
The WebSocket (WS) protocol runs on TCP (like HTTP), and the WSS connection runs on TLS/SSL, which, in turn, runs on TCP. The WebSocket protocol is compatible with HTTP such that the WebSocket connection uses the same ports: the WebSocket default port is 80 and WebSocket Secure (WSS) uses port 443 by default.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With