Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome app sockets.tcpServer does not receive data

I tried to use Chrome's sockets.tcpServer API to communicate with local applications. Here is the link to my code: http://pastebin.com/1mWXeZKr.

I use nc 127.0.0.1 7000 to test if the server is working. However, although I can connect to the server and receive the message from the server, the server does not receive any message as I send them from the client(nc). I am not sure if I am using the API correctly. Could anyone notice any errors in the code?

Here is a snippet of the code:

function onAccept(info) {
  if (info.socketId != serverSocketId)
    return;
  console.log("Client connected.");
  // Start receiving data.
  _stringToArrayBuffer("connected.\n", function(buf) {
    chrome.sockets.tcp.send(info.clientSocketId, buf, function(info) {
      if (info.resultCode != 0)
        console.log("Send failed.");
    });
  });

  chrome.sockets.tcp.onReceive.addListener(onReceive);
}

function onReceive(info) {
  console.log("Data received.");
  _arrayBufferToString(info.data, function(str) {
    console.log(str);
  });
}

UPDATE:

Okay, I found the solution. See the answer below.

like image 736
changlan Avatar asked Mar 20 '14 21:03

changlan


1 Answers

I found the solution. The socket clientSocketId is paused by default when it is created. In the onAccept function, simply adding chrome.sockets.tcp.setPaused(info.clientSocketId, false); after adding onReceive listener solves problem.

function onAccept(info) {
  if (info.socketId != serverSocketId)
    return;

  chrome.sockets.tcp.onReceive.addListener(onReceive);
  chrome.sockets.tcp.onReceiveError.addListener(function(info) {
    console.log("Error: ", info);
  });

  chrome.sockets.tcp.setPaused(info.clientSocketId, false);

  buf = str2ab("Connected.\n");
  chrome.sockets.tcp.send(info.clientSocketId, buf, function(info) {
    if (info.resultCode != 0)
      console.log("Send failed.");
  });
}
like image 145
changlan Avatar answered Nov 03 '22 07:11

changlan