WebSocket wss:// connection always fails in Desktop HTML File - javascript

File in Desktop Image : index.html
Error Message Image : WebSocket connection to 'wss://graphigostream.prd.dlive.tv/' failed:
connect # index.html:9
File Path : file:///C:/Users/.../Desktop/index.html
Code:
<!doctype html>
<html>
<head>
</head>
<script>
function connect() {
var ws = new WebSocket('wss://graphigostream.prd.dlive.tv/', "graphql-ws");
ws.onopen = function() {
// ...
};
ws.onmessage = function(e) {
// ...
}
ws.onclose = function(e) {
// ...
};
ws.onerror = function(err) {
// ...
};
}
connect()
</script>
<body>
</body>
</html>
I want run this WebSocket through an HTML file, this url works in Nodejs, another website has the same and it works, I checked "window.WebSocket"

Related

Why WebSocket Server is not loading

I have two files named test.html and server.py and I am trying to make a WebSocket server.
Hence test.html is a client-side and server.py is server-side.
But Websocket server is not loading, please find below code :
test.html
<p id="status">Connecting...</p>
<input id="message" />
<button id="submit">Send</button>
<script>
var socket = new WebSocket('wss://starlite3.tk/IncreedibleTanksServer');
socket.onopen = function() {
document.getElementById("status").innerHTML="Connected";
}
document.getElementById("submit").addEventListener("click", function() {
socket.send(document.getElementById("message").value);
});
socket.onmessage = function(e) {
alert(e.data);
}
socket.onerrror = function(e) {
document.getElementById("status").innerHTML = "ERROR: "+e.target.CONNECTING
}
</script>
server.py
import websockets
def start(websocket, uri):
websocket.send('HI')
websockets.server.serve(start, "starlite3.tk", 0);

WebSocket Error on Android Device, Works in IE

I have an issue with a websocket client.
It seems to work fine in IE and Edge. The server responds with a message and the client receives and displays this message, but when my android device runs this code, the error handler gets fired off and the connection is closed immediately.
The error handler gives me a message: "undefined"
Here is my Client:
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Touch Tracing </title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script type='text/javascript'>
function openSocket(){
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
//var WebSocket = require('ws');
var ws = new WebSocket("ws://localhost:8080/WebSocketServer/control");
ws.onopen = function ()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message = " + received_msg);
};
ws.onclose = function ()
{
// websocket is closed.
alert("Connection is closed...");
};
ws.onerror = function(evt)
{
alert("Error: " + evt.data);
};
} else
{
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<meta name="viewport" content="width=device-width,user-scalable=no">
<div>
Keyboard
</div>
</body>
</html>
My Server simply just responds with a message:
#OnMessage
public String onMessage(String message) {
return "Got it.";
}

Websockets over WSS:// doesn't appear to fire events on server

I am trying to set up a basic WSS websockets server. This is my minimal HTML (with the embedded javascript):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body style="background-color:white">
<h1>Test of WSS server</h1>
<p>Status: <span id=status"></span></p>
Click to send message
<script src="/newjs/jquery-2.1.1.js"></script>
<script>
var connection;
$(document).ready(function () {
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
alert("browser says no");
console.log("Browser does not supports websockets");
return;
}
setupConnection();
});
function message() {
var msg = "Test Message";
connection.send(msg);
}
function setupConnection() {
connection = new WebSocket('wss://www.example.com:14000');
connection.onerror = function(error) {
console.log('onerror fired');
};
connection.onopen = function(event) {
$("#status").html("Open");
};
connection.onmessage = function (message) {
alert(message.data);
};
}
setInterval(function() {
if (connection.readyState !== 1) {
setupConnection();
}
}, 5000);
</script>
</body>
</html>
The following is the JS server run by nodejs:
var fs=require("fs");
var ws_cfg = {
ssl: true,
port: 14000,
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
ca_cert: '/httpd/conf/ssl.crt/gd_bundle-g2-g1.crt'
};
var processRequest = function(req, res) {
console.log("Request received.")
};
var httpServ = require('https');
var app = null;
app = httpServ.createServer({
key: fs.readFileSync(ws_cfg.ssl_key),
cert: fs.readFileSync(ws_cfg.ssl_cert),
ca: fs.readFileSync(ws_cfg.ca_cert),
},processRequest).listen(ws_cfg.port);
var WebSocketServer = require('ws').Server, ws_server = new WebSocketServer( {server: app});
ws_server.on('open',function(request) {
console.log("opening");
});
ws_server.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
if (request.origin!='https://www.example.com') {
console.log("rejecting request from " + request.origin + " as not coming from our web site");
return;
}
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
console.log("Got a message");
});
});
I fire up the server with node then load the web page in my browser (using either FF or Chrome). Using the developer tools I see that the connection appears to be made. On the server side I see the established connection using netstat. I also put an alert() in the browser side in the onopen() function and it fired.
The problem is that no console log output is produced. When connection.send(mag) is executed the on("message" event never appears to fire on the server. I'm at a loss here. I had this working as an http:// websocket server but this is my first attempt at wss:. I would appreciate any insight.
Notes:
The sever name is not example.com although that is what I show in my code.
The firewall is allowing anyone to connect on port 14000 using TCP protocol.
The cert is a working wildcard cert for the web site.
Finally figured out what it was after ignoring it for a month or so. It had to do with the symbolic link (/httpd) defined for the SSL files as in:
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
They had to be changed to:
ssl_key: '/usr/local/apache2/conf/ssl.key/my.key',
ssl_cert: '/usr/local/apache2/conf/ssl.crt/my.crt',
Who knew that symbolic links were frowned upon? Well, now we all do.

Failed to load resource - Socket.IO

I have been trying my hand at node.js and socket.io, and following a tutorial. I keep getting an error from an application i am building. This is my server.js file:
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
var chatServer = require('./lib/chat_server.js');
chatServer.listen(server);
//file doesn't exist
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
//handles serving file data
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
//cache static files to memory
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
}
else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
}
else {
send404(response);
}
});
}
}
var server = http.createServer(function(request, response) {
var filePath = false;
if (request.url == '/') {
filePath = 'public/index.html';
}
else {
filePath = 'public' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(3001, function() {
console.log("Server listening on port 3001.");
});
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Chat</title>
<meta name="description" content="An interactive chat application using websockets.">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<div id='content'>
<div id='room'></div>
<div id='room-list'></div>
<div id='messages'></div>
<form id='send-form'>
<input id='send-message' />
<input id='send-button' type='submit' value='Send'/>
<div id='help'>
Chat commands:
<ul>
<li>Change nickname: <code>/nick [username]</code></li>
<li>Join/create room: <code>/join [room name]</code></li>
</ul>
</div>
</form>
</div>
<script src="[localserver here]:3001/socket.io/socket.io.js" type="text/javascript"></script>
<script src="/javascripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="/javascripts/chat.js" type="text/javascript"></script>
<script src="/javascripts/chat_ui.js" type="text/javascript"></script>
</body>
</html>
Upon loading "[localserver here]:3001" from the browser, the index page appears with the ensuing CSS. But when i try an event, like sending a message, i get this error:
Error 404: resource not found.
I right-clicked and inspected element from my Chrome browser and got this two messages:
Failed to load resource: the server responded with a status of 404 (Not Found) "[localserver here]:3001/socket.io/socket.io.js"
Uncaught ReferenceError: io is not defined "[localserver here]:3001/javascripts/chat_ui.js:26"
This is line 26 from my chat_ui.js file:
var socket = io.connect('[localserver here]:3001');
$(document).ready(function() {
var chatApp = new Chat(socket);
socket.on('nameResult', function(result) {
var message;
if (result.success) {
message = 'You are now known as ' + result.name + '.';
} else {
message = result.message;
}
$('#messages').append(divSystemContentElement(message));
});
socket.on('joinResult', function(result) {
$('#room').text(result.room);
$('#messages').append(divSystemContentElement('Room changed.'));
});
socket.on('message', function (message) {
var newElement = $('<div></div>').text(message.text);
$('#messages').append(newElement);
});
socket.on('rooms', function(rooms) {
$('#room-list').empty();
for(var room in rooms) {
room = room.substring(1, room.length);
if (room != '') {
$('#room-list').append(divEscapedContentElement(room));
}
}
$('#room-list div').click(function() {
chatApp.processCommand('/join ' + $(this).text());
$('#send-message').focus();
});
});
setInterval(function() {
socket.emit('rooms');
}, 1000);
$('#send-message').focus();
$('#send-form').submit(function() {
processUserInput(chatApp, socket);
return false;
});
})
I have tried all sorts. Initially line 26 was var socket = io.connect(); and i changed it to the one above. I also changed the directory of socket.io.js in the index.html file from:
to
...as i thought this was the problem, but it is still giving me the same error.
Please how do i resolve this?
(PS - I am using Brackets as my IDE for node.js development. Also, i used "[localserver]" to indicate the localhost)
Try this:
<script type="text/javascript" src='http://localhost:3001/socket.io/socket.io.js'>
</script>
<script type="text/javascript">
var socket = io.connect('http://localhost:3001');
socket.on('connect',function(){
console.log("connect");
});
</script>
It must help you.
The line chatServer.listen(server); should be after you run your server.
chartServer is listening to the server but that one is not running yet.
Try to move this line:
chatServer.listen(server);
to the end of your script server.js

Getting error in establishing a cross-domain connection using SignalR 2.0

When I am going to use it's for cross domain then i am getting error message when i call start() function. Error in jquery.signalR-2.0.2.min.js.
Error message is
"Uncaught Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. ."
I am using server side code
Startup.cs class code is:
[assembly: OwinStartup(typeof(SignalRNew.Startup))]
namespace SignalRNew
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});
}
}
}
I am using client side script is:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="/Scripts/jquery-1.6.4.min.js"></script>
<script src="/Scripts/jquery.signalR-2.0.2.min.js"></script>
</head>
<body>
<div></div>
<script type="text/javascript">
$.connection.hub.url = 'http:\\localhost:2100\signalr';
$.connection.hub.start().done(function () {
alert('Now connected');
});
</script>
</body>
</html>
kindly reply...
Try to enable the logging in the client side, and look for error messages or warnings:
http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#logging
Enable logging (with the generated proxy)
$.connection.hub.logging = true;
$.connection.hub.start();
Enable logging (without the generated proxy)
var connection = $.hubConnection();
connection.logging = true;
connection.start();
Please try creating the proxy by following steps.
var connection=$.hubConnection();
var proxy=connection.createHubProxy("hubName");
connection.start().done(function () {
alert('Now connected');
});
You have connected the url without giving the hub name .That may be the problem.

Categories

Resources