0

I have a very basic tcp server that can send and receive json data.

See my code:

  // Handle incoming messages from clients.
  socket.on('data', function (data) {

    var obj = JSON.parse(data);

    if(obj.type == "register") {
        _clientObj[obj.msg] = {
            client: 'Client',
            socketID: socket.name
        }


        console.log("Register...");     

    } else if(obj.type == "message") {


        console.log(socket.name + " --> message: " + obj.msg);  
    }

  });

The problem seems to be that sometimes data is not complete and it trows an error:

SyntaxError: Unexpected end of input

How can i wait before data is finished before i parse out the json?

1 Answer 1

3

You could wait for emitting end event, and then parse it.

Example:

// Handle incoming messages from clients.
data = '';
socket.on('data', function (chunk) {
    data += chunk;
});

// Handle incoming messages from clients.
socket.on('end', function () {
    var obj = JSON.parse(data);

    if(obj.type == "register") {
        _clientObj[obj.msg] = {
            client: 'Client',
            socketID: socket.name
        }

    console.log("Register...");   

    } else if(obj.type == "message") {
        console.log(socket.name + " --> message: " + obj.msg);  
    }
});

Documentation: http://nodejs.org/api/all.html#all_event_end_1

Sign up to request clarification or add additional context in comments.

Comments

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.