Skip to content Skip to sidebar Skip to footer

How To Flush A Socket In My Code

I'm writing through a socket from a FF add-on to a java server. I write several requests and the server seems to process them one-by-one. In contrast, the responses from the server

Solution 1:

You are writing to the output stream synchronously, that means that no other JavaScript code can run while you do it. So receiving anything from the server while you are writing is impossible, incoming data is simply put into a buffer.

The other issue is that you are sending the next string without waiting for the response from server. Normally, you will be able to send off both of them before the server response arrives. You probably want to send the next string only when you receive the response to the previous one.

You probably want to use a send function like this one:

Components.utils.import("resource://gre/modules/NetUtil.jsm");

var toSend = ["hi1\n", "hi2\n"];

functionsendNextString(outstream)
{
  if (!toSend.length)
    return;  // Nothing left to sendvar outputData = toSend.shift();
  console.log(outputData);
  var instream = Components.classes["@mozilla.org/io/string-input-stream;1"]
                           .createInstance(Components.interfaces.nsIStringInputStream);
  instream.setData(outputData, outputData.length);

  NetUtil.asyncCopy(instream, outstream);
}

And you would call sendNextString(outstream) in your code after pump.asyncRead() as well as in onDataAvailable.

PS: From what I can tell, flushing the stream is not the issue here - you are using a non-buffering stream.

Solution 2:

TCP is a stream protocol, so you receive a stream of bytes. If you want packets, you got to implement your own protocol over TCP to be able to separate them. This topic is widely covered on internet.

Edit

This is a common pitfall in socket programming. Most people do not understand at first that a TCP socket is a stream, not a message queue.

I mean, one call to "send" at one end of the socket do not correspond necessarily to one "receive" at the other end. The underlying layers can decide to group or split the bytes sent at will.

So you can have something like this:

  • client sends "ABCD"
  • client sends "EFGH"
  • server receives "AB"
  • server receives "CDEF"
  • server receives "GH"

This is a stream, not a message queue. Think of it as a an infinite file you're reading in.

So, if you want to read strings out of a file, you need some way to separate them. It can be a delimiter, or you can prefix your strings by the string's length, or whatever.

Post a Comment for "How To Flush A Socket In My Code"