netty secure websockets using http.. possible? - javascript

I have configured my websocket connection following the example:
https://github.com/netty/netty/tree/3/src/main/java/org/jboss/netty/example/http/websocketx/sslserver
This all works, i have the browser connecting to a secured websocket using https address.
$(document).ready(function () {
var location = "wss://localhost:9999/websocket"
ws = new WebSocket(location);
ws.onopen = function(event) {
}
ws.onclose = function(event) {
}
ws.onmessage = function(event) {
}
});
I want to connect to this page that makes the websocket connection using http?... is that possible ?... I have tried this, and it doesn't seem to work.. so im not sure...
I have read that it is possible to create a WSS connection when regardless of going to the page using http or https?.. is this correct?

Related

Javascript websocket not connecting

I'm trying to make a simple chat application
I have a server made with Spring running with a websocket
I've also made an android app that successfully connects to the websocket and receives and sends messages
To make testing easier I decided to make a web client for the server in html/js, but the websocket connection fails
I'm using the exact same address as I am in the android app
Heres my JS code:
$( document ). ready(function(){
var ws = new WebSocket("ws://192.168.1.3:8080/chatwebsocket")
ws.onmessage = function (event) {
var msg = event.data
$("#chat_container").append(`<p>$(msg.sender): $(msg.content))</p>`)
}
ws.onerror = function (event) {
console.log('WebSocket error: ', event);
}
ws.onclose = function (event) {
console.log('WebSocket closed: ', event);
}
$("#message_form").onsubmit = function(data) {
var msgContent = data.messageContent
var msg = {"sender":"webclient", "content": msgContent}
ws.send(JSON.stringify(msg))
}
})
I've tested it with Chrome and Firefox and both fail
Chrome just gives the message: WebSocket connection to 'ws://192.168.1.3:8080/chatwebsocket' failed:
Theres no useful info in either the error or close events
No connection is made on the server side
The web client successfully connects to wss://ws.postman-echo.com/raw for an example
Can someone please point me in the right direction with troubleshooting this because I feel like I have no info to work with

WebSocket not connecting

I have a WebSocket server that I am trying to make and I can't figure out why it is not connecting.
index.html(client):
<p id="status">Connecting...</p>
<input id="message" />
<button id="submit">Send</button>
<script>
var s = new WebSocket("wss://StarliteServer.cs641311.repl.run:8000", ["soap", "wamp"]);
s.onopen = function() {
document.getElementById("status").innerHTML="Connected";
}
document.getElementById("submit").addEventListener("click", function() {
s.send(document.getElementById("message").value);
});
s.onmessage = function(e) {
alert(e.data);
}
s.onclose = function(e) {
document.getElementById("status").innerHTML = "ERROR: "+e.code
}
</script>
app.js
var http = require('http');
http.createServer(function(req, res) {
req.onopen = function() {
console.log("OPENING CONNECTION");
res.writeHead(200);
}
req.on('data', function(e) {
res.write(e);
});
req.on('close', function() {
console.log('CONNECTION CLOSED');
});
}).listen(8000);
A websocket client requires a websocket server to connect to. While all webSocket connections do start with a plain http request, the server must then "upgrade" the connection to the webSocket protocol and the server must be able to speak that webSocket protocol. If not, the client will drop the connection since the server fails to support the proper protocol.
There are multiple websocket server libraries for node.js in NPM. Pick one of those and add it to your server. If your server intends to also serve as a regular http server, you can share the same http server with the websocket server. The webSocket server code will examine each incoming request and pick off the ones that show that they represent the initiation of a webSocket connection and it will take them over from there.
To give you an idea what a webSocket server must do, you can see this article on writing websocket servers. I'm not suggesting you write your own (too much time spent on protocol detail), but this will certainly explain why a plain http server won't suffice for a webSocket connection.

Unable to establish Handshake with Public Websocket API for Kraken

I'm trying to make a watchlist for cryptocurrency tickers You type a ticker, add it, and it will show you real time prices in a table format.
My first step is to try and establish a handshake connection with the Kraken websocket API (documentation here: https://www.kraken.com/features/websocket-api#connectionDetails)
My ask:
At the moment, all I want to do is be able to console log a "connection success" for when I'm connected with the websocket API from Kraken (crypto exchange). I'm trying to do this via the portion below (scroll all the way down to see all of the code)
socket.onopen = function(event) {
socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.url;
socketStatus.className = 'open';
};
I've got an index.html file, and an app.js file. When I open the index.html file in chrome, I get an error:
app.js:5 WebSocket connection to 'ws://ws-sandbox.kraken.com/' failed: Error during WebSocket handshake: Unexpected response code: 521
I've tried with only this line of code for websocket related stuff
var socket = new WebSocket('ws://ws-sandbox.kraken.com')
I've also tried to use the get method, provided in examples from here
https://medium.freecodecamp.org/here-is-the-most-popular-ways-to-make-an-http-request-in-javascript-954ce8c95aaa
$.get('ws://ws-sandbox.kraken.com',function(data){console.log(`${data}`)})
in my app.js file, my question is, apart from line below what else do I need to successfully do the handshake? Do I need to send a GET request with header information (please see very end)?
var socket = new WebSocket('ws://ws-sandbox.kraken.com')
in the documentation, you'll see connection details. Connection details for sandbox environment. The URL is ws-sandbox.kraken.com
link: https://www.kraken.com/features/websocket-api#connectionDetails
I've followed the example here:
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
GET REQUEST QUESTION:
I was looking at this site as an example:
https://blog.teamtreehouse.com/an-introduction-to-websockets
and it said I need to send an HTTP request to the server using something similar to this. I'm just not sure if this is required for what I'm trying to do.
GET ws://websocket.example.com/ HTTP/1.1
Origin: http://example.com
Connection: Upgrade
Host: websocket.example.com
Upgrade: websocket
CODE IN APP.JS FILE
$(document).ready(function(){ console.log('page ready')
var socket = new WebSocket('ws://ws-sandbox.kraken.com')
$.get('ws://ws-sandbox.kraken.com',function(data){console.log(`${data}`)})
var form = document.getElementById('message-form');
var messageField = document.getElementById('message');
var messagesList = document.getElementById('messages');
var socketStatus = document.getElementById('status');
var closeBtn = document.getElementById('close');
socket.onopen = function(event) { //LOGGING SUCCESSFUL CONNECTION HERE
socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.url;
socketStatus.className = 'open';
};
})
I know this is an old question but I was having the same issue and wanted to provide my solution in case anyone else comes here in need of it.
So the reason I found for this error was because I using a protocol that was not supported by the API. I was using TLS 1.0 where the Kraken API only supports 1.2/1.3:
https://support.kraken.com/hc/en-us/articles/360023264371-TLS-upgrade-that-might-affect-your-API-connections
So to solve it, I simply set my websocket client to use TLS 1.2 as the protocol.
From a browser, using the Websocket() built-in api:
new WebSocket("wss://ws.kraken.com").onopen = function(){
this.onclose = () => console.log("SOCKET CLOSED")
this.onmessage = (e) => console.log(JSON.parse(e.data))
this.send(JSON.stringify({
"event": "subscribe",
"pair": ["XBT/USD"],
"subscription": {
"interval": 1,
"name": "ohlc"
}
}), (e) => console.log(e))
}

websockets - ws with node

I'm trying to push messages from server to client using ws module in node.js application.
Please find below the code in app.js.
var server = app.listen(port);
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({ server: server});
wss.on('connection', function (ws) {
console.log('connected');
});
ws.on('message', function (data, flags) {
});
});
code in the client side js file.
window.WebSocket = window.WebSocket || window.MozWebSocket;
var host = window.document.location.host.replace(/:.*/, '');
var port = window.document.location.port;
var socketConnection = new WebSocket('ws://'+ host+':'+ port);
socketConnection.onerror = function (error) {
// TODO : report error here..
};
socketConnection.onmessage = function (message) {
var obj = JSON.parse(message.data)
};
The problem is when i'm running the node application locally.i.e http://localhost:port and when I try to handshake with ws connection through "ws://localhost:port\". The handshake happens and i am able to send and receive messages.
But when i access the same application using the ip of my machine i.e as http://10.xx.yy.zz:port. Im able to open the application and do evrything but the handshake with websockets time out. The same happens when the app is running in another machine and i try to connect to it from my machines browser.The handshake doesnot happen and it times out.
I have tried the same with demos provided out of box by ws module. The same happens. Am I missing something when creating the websocket server?

javascript: print websocket client IP

node.js WebSocket example code snippet
I have a simple node.js application using express. Now everytime a client connects to the node server I see the string 'new client connected' but I would like to know which IP the new client had.
var WebSocketServer = require('ws').Server;
var connIds = [];
var server = require('http').createServer(app).listen(80);
// set up the websocket server
var wss = new WebSocketServer( { server: server } );
wss.clientConnections = {};
// websocket server eventlisteners and callbacks
wss.on('connection', function (connection) {
console.log('wss.on.connection - new client connected');
...
See the code at:
https://github.com/qknight/relais.js/blob/master/relais.js/server.js#L159
question
The object connection has properties but I don't understand how to query them or what they are. All I want is to print the client IP and maybe, if existent, other similar properties as well.
How do I do that?
Remote IP is a property of the pre-upgrade connection:
var wss = new WebSocketServer({port: 9876});
wss.on('connection', function(ws) {
console.log(ws.upgradeReq.connection.remoteAddress);
});
i don't recall how i found it, but i know it took me a while; i wish the docs were as good as the code...
UPDATE:
WS has moved some things around, so here's an updated example of how to get the original HTTP info in current code. Note the 2nd argument to the connection event handler:
wss.on('connection', function conn(ws, req) {
var ip = req.connection.remoteAddress;
console.info(ip);
});

Categories