im writing websocket client, and I would like to receive messages as json strings. To do this, I need a login. And if the login is incorrect, I am sending a json string with nosuccess. JSON String:
{"action":"login","args":["nosuccess"]}
On the client, I use this to get the line:
WebSocket socket = new WebSocket("ws://localhost:2555/api"); socket.onmessage = function(evt) { console.log(evt.data); console.log(typeof(evt.data)); onMessage(evt); } function onMessage(evt) { var data = JSON.parse(evt.data); var action = data.action; var args = data.args; console.log(data); console.log(typeof(data)); console.log(action); console.log(args);
But the data type is a string ... But why?
evt.data returns:
"{\"action\":\"login\",\"args\":[\"nosuccess\"]}"
:
{"action":"login","args":["nosuccess"]}
A WebSocket server is a berth server that sends a string and a string array to json processed by json using gson.toJson (class) Gson from Google. A class is a class that contains the String action and args of the String array.
Full source code websocket.js:
var socket; function openWebsocket(adress) { socket = new WebSocket(adress); socket.onopen = function(evt) { console.log("Socket opened [" + adress + "]"); }; socket.onclose = function(evt) { loadPage("login.html"); console.log("Socket closed [" + evt.code + "]"); } socket.onmessage = function(evt) { onMessage(evt); } socket.onerror = function(evt) { console.log("Socket couldn't connect [" + evt.message + "]"); showMessage("fa-exclamation-circle", "Socket couldn't be established!", 1000); } } function onMessage(evt) { var data = JSON.parse(evt.data); var action = data.action; var args = data.args; console.log(data); console.log(typeof(data)); console.log(action); console.log(args); $(".card-container h3").html(data); if(action == "login") { if(args[0] == "success") { loadPage("dashboard.htm"); currentpage = "dashboard.htm"; showMessage("fa-check", "Du wurdest erfolgreich eingeloggt", 2000); } else if(args[0] == "nosuccess") { loadPage("login.html"); currentpage = "login.html"; showMessage("fa-exclamation-circle", "Falscher Benutzername oder falsches Passwort", 2000); } else if(args[0] == "unauthenticated") { loadPage("login.html"); currentpage = "login.html"; showMessage("fa-exclamation-circle", "Login failure: not authenticated", 2000); } } } function sendMessage(json) { $(".card-container h3").html(JSON.stringify(json)); console.log(JSON.stringify(json)); socket.send(JSON.stringify(json)); }
If I change this line:
var data = JSON.parse(evt.data);
:
var data = JSON.parse("{\"action\":\"login\",\"args\":[\"nosuccess\"]}");
Then it is a json object, but when I use evt.data it is a string. If I changed the line to this:
var data = JSON.parse(JSON.parse(evt.data));
Then it works, but why, as a rule, it should do it with only one JSON.parse, right?