Integrate & access websocket in custom web application

Tallakokula5 years ago

Hi All,
Im creating a custom web application and trying to integrate web-socket devices realtime data from devices.

As i have done the integration separately through nodejs and successfully getting the data from websocket which requires authentication using /session service and based on the response of the session api using the cookie attribute i m able to connect to web-socket and get the real-time data.

But when i integrate my custom web application with some open layers gis , i tried calling the web-socket with authentication through XML Http Request but in the response im not getting the same output as in the above request for session api.

I tried referring the github code app.js in sample folder, as it is taking token which is placed in the header of the url.

Please help me out to use which authenticate mechanism to call session API, so that i will get the token which i can pass to ws://xxxx.xxx.xxx/socket url.

Note : As i have to call the websocket on client end , so would require help on token generation only.

Code used on server side through nodejs ,

app.post('/', function (req, res) {
	request({
		headers: {
		  'Content-Length': contentLength,
		  'Content-Type': 'application/x-www-form-urlencoded'
		},
		uri: 'http://my-ip-address:8082/api/session',
		body: formData,
		method: 'POST'
	  }, function (err, resp, body) 
	  {
			const url = 'ws://my-ip-address:8082/api/socket'
			const connection = new WebSocket(url, [], {'headers': { 'Cookie': resp.headers['set-cookie'][0] }})
			 
			connection.onopen = () => {
			  connection.send('Message From Client') 
			}
			 
			connection.onerror = (error) => {
			  console.log('WebSocket error: ${error}')
			}
			connection.onmessage = (e) => {
			  console.log(e.data)
			}
	  });
  })

Kindly help to resolve this issue.

Anton Tananaev5 years ago

So, what's response you get from the server?

Tallakokula5 years ago

Hi Anton,

Thanks for your kind reply and immediate response,

Please find the below code on the client side,

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://my-ip-address:8082/api/session", true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(formData);
xhr.onload = function () {
var resp = this.response;
var data1 = JSON.parse(this.responseText);
console.log(data1);
var headers = xhr.getAllResponseHeaders();
console.log(headers);

var url = 'ws://my-ip-address:8082/api/socket'
var connection = new WebSocket(url, [], { 'headers': { 'Cookie': resp.headers['set-cookie'][0] } })
connection.onopen = () => {
    connection.send('Message From Client')
}

connection.onerror = (error) => {
    console.log('WebSocket error: ${error}')
}
connection.onmessage = (e) => {
    console.log(e.data)
}

}

Response which i got from session api is this as below ,

Response Headers:
content-type: application/json
expires: Thu, 01 Jan 1970 00:00:00 GMT

Response JSON :
{
"id": 1,
"attributes": {},
"name": "admin",
"login": null,
"email": "admin",
"phone": null,
"readonly": false,
"administrator": true,
"map": null,
"latitude": 0,
"longitude": 0,
"zoom": 0,
"twelveHourFormat": false,
"coordinateFormat": null,
"disabled": false,
"expirationTime": null,
"deviceLimit": -1,
"userLimit": 0,
"deviceReadonly": false,
"token": null,
"limitCommands": false,
"poiLayer": null,
"password": null
}

Any help in resolving this issue is kindly appreciated, thanks in advance.

Tallakokula5 years ago

Hi Anton,

Expected response in header is this (which i m not getting it, when calling from browser level through javascript),

{ connection: 'close',
date: 'Fri, 06 Mar 2020 07:09:01 GMT',
'set-cookie': [ 'JSESSIONID=node010yhqjnipjufgoi12uehyrmci140.node0; Path=/' ],
expires: 'Thu, 01 Jan 1970 00:00:00 GMT',
'content-type': 'application/json',
'access-control-allow-headers': 'origin, content-type, accept, authorization',
'access-control-allow-credentials': 'true',
'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS',
'access-control-allow-origin': '*',
'content-length': '379',
server: 'Jetty(9.4.20.v20190813)' }

Kindly check and if possible suggest some solution, thanks in advance.

Tallakokula5 years ago

Hi Anton,

Could you pls provide your expert advice, it would be very helpful to go ahead.