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
Related
I have a simple snippet on the front end as follows which I can verify is working. I can do this by changing the port to something other than 3000 and it will error.
It is definitely finding the server at that port:
// Create WebSocket connection .. will error if I change the port
const socket = new WebSocket('ws://localhost:3000');
console.log('DEBUG: Web socket is up: ');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
I am using ws-express on the server side as follows. This was the minimal example given in the NPM docs:
const expressWs = require('express-ws')(app);
app.ws('/echo', (ws, req) => {
ws.on('message', (msg) => {
ws.send(msg);
});
});
However, the open event on the client never fires. I would like to send messages from the client to the server, but I assume, that I need an open event to fire first.
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))
}
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?
This code works great and connects to the socket server that I have running:
var socket = io('http://localhost:8888');
socket.on('news', function (data) {
console.log(data);
socket.emit('evento', { my: 'data' });
});
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('connect', function () {
console.log('user connect');
var data = 'ddsds';
socket.emit('evento', { my: 'data' });
});
On the other hand when I try to use WebSocket() it fails to connect. This is the code that doesn't work:
var socket = new WebSocket('ws://localhost:8888');
// Open the socket
socket.onopen = function(event) {
// Send an initial message
socket.send('I am the client and Im listening!');
}
// Listen for messages
socket.onmessage = function(event) {
console.log('Client received a message',event);
};
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
socket.onerror = function(event) {
console.log('error: ',event);
};
It's not an error in the code; I think there is a different way to connect. I need this to work using WebSocket();. Any help would be greatly appreciated!!
socket.io is something that runs on top of WebSocket (using WebSocket as one of the transports it supports). It adds new semantics on top of WebSocket so you can't use the socket.io methods and events directly with a WebSocket object.
socket.io will select the WebSocket transport if it is available so you should not need to use your second example - the first should work just fine and will use WebSockets automatically (when available).
See this answer and this answer for how to use the minimized, gzipped and cached version of socket.io which makes it smaller and faster.
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?