1

I write a Websocket Whiteboard application, but I have problems with JSON.parse.

let server = require('ws').Server;
let s = new server({port: 3000 });

// alle bisher gezeichneten Lines
let line_history = [];


s.on('connection', function(ws) {

     for (let i in line_history) {
          //var object = { line: line_history[i]}
          //ws.send(JSON.stringify(line_history[i]) );
     }   


     ws.on('message', function (data) {
//console.log(data);
    //ws.send("Test");

      // add received line to history 
       var test = JSON.parse(data);
       console.log(test.line[0].x);
      line_history.push(test);
      //console.log(line_history[0]);
      // send line to all clients
      //object = { line: data };
      ws.send(JSON.stringify(test));

   });



});


And thats my client

document.addEventListener("DOMContentLoaded", function() {
   var mouse = { 
      click: false,
      move: false,
      pos: {x:0, y:0},
      pos_prev: false
   };
   // get canvas element and create context
   var canvas  = document.getElementById('drawing');
   var context = canvas.getContext('2d');
   var width   = window.innerWidth;
   var height  = window.innerHeight;
   var socket  = new WebSocket("ws://localhost:3000");

   // set canvas to full browser width/height
   canvas.width = width;
   canvas.height = height;

   // register mouse event handlers
   canvas.onmousedown = function(e){ mouse.click = true; };
   canvas.onmouseup = function(e){ mouse.click = false; };

   canvas.onmousemove = function(e) {
      // normalize mouse position to range 0.0 - 1.0
      mouse.pos.x = e.clientX / width;
      mouse.pos.y = e.clientY / height;
      mouse.move = true;
   };

   // draw line received from server

      socket.onmessage = function (data) {



      // 34
      var line = JSON.parse(data);



      console.log(line);
      /*context.beginPath();
      context.moveTo(line[0].x * width, line[0].y * height);
      context.lineTo(line[1].x * width, line[1].y * height);
      context.stroke();*/
   };


   // main loop, running every 25ms
   function mainLoop() {
      // check if the user is drawing
      if (mouse.click && mouse.move && mouse.pos_prev) {
         // send line to to the server
         var object = { line: [ mouse.pos, mouse.pos_prev ] };
         socket.send(JSON.stringify(object));
//socket.send("Vom Client");
         mouse.move = false;
      }
      mouse.pos_prev = {x: mouse.pos.x, y: mouse.pos.y};
      setTimeout(mainLoop, 15);
   }
   mainLoop();
});

Now I am having the problem, which the Console says is:

Unexpected token o in JSON in line 34 (line with comment 34)

So I think it's already a object and I don't have to parse it, but when I don't parse it I have the problem that I can not access the values of this line object. Always undefined or not there. When I only print data without parsing before I get this

MessageEvent {isTrusted: true, data: "{"line":[{"x":0.3506849315068493,"y":0.12663755458…"x":0.3506849315068493,"y":0.12663755458515283}]}", origin: "ws://localhost:3000", lastEventId: "", source: null, …}

but i need the values of this object.

Thanks for any help :)

1 Answer 1

2

socket.onMessage recieves an event as argument, that is why you can not parse your data variable.

MessageEvent {isTrusted: true, data: "{"line":[{"x":0.3506849315068493,"y":0.12663755458…"x":0.3506849315068493,"y":0.12663755458515283}]}", origin: "ws://localhost:3000", lastEventId: "", source: null, …}

As you can see, there is json in here, in the data property. That is the part you need to parse. So the code should go:

socket.onmessage = function(event){
    const data = JSON.parse(event.data)
    const line = data.line;
} 
Sign up to request clarification or add additional context in comments.

1 Comment

glad i could help, mark it as an answer if you think it's all you need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.