I've got a bit of a problem with my websocket code intermittently not sending data... As it stands I've written a small C# server which handles the websocket and prints a label.
When running the code on my computer it works fine every time but when I tried it on two other computers I had problems.
I set up some packet sniffing software and what I seem to see as follows:
When the application works... The browser creates a connection to the server which completes the hand shake. Once completed the websocket.onopen event fires. During this event I send data to the server (which I can see in Network Monitor) and then check for buffered data before closing the websocket.
When the application doesn't work... Exactly the same thing happens, however I can't see the data in Network Monitor. The handshake is there, and the onopen event fires and closes the connection but no data is sent over the network...
I installed Network Monitor on both the client and server machine and neither machine can see the missing the data.
Can anyone see any problems in my code below? Failing that does anyone know if this is a bug?
The code I wrote is as follows:
var _socket;
function sendXmlToLabelPrinter(strXML)
{
if (_socket == null)
{
console.log("creating socket");
_socket = new WebSocket("ws://127.0.0.1:50/"); // LOCAL
_socket.binaryType = "arraybuffer";
_socket.onopen = function()
{
console.log("socket opened");
if (_socket.readyState == WebSocket.OPEN)
{
try
{
_socket.send(strXML);
}
catch (ex)
{
console.log("an error occured when sending");
console.log(ex);
}
var intClose = setInterval
(
function()
{
console.log("checking socket buffer");
if (_socket.bufferedAmount == 0)
{
console.log("closing socket");
_socket.close();
_socket = null;
clearTimeout(intClose);
}
},
250
);
hideUserMessage();
}
else
{
console.log("socket not ready");
}
};
_socket.onerror = function(myErr)
{
console.log("error connecting to label printer, set timer to try again");
_socket.close();
_socket = null;
showUserMessage("Error: Please check label printer is running (Retrying in 5s)");
setTimeout(function(){hideUserMessage()}, 2000);
setTimeout(function(){sendXmlToLabelPrinter(strXML)}, 5000);
};
}
else
{
console.log("socket is in use, set timer to retry");
setTimeout(function(){sendXmlToLabelPrinter(strXML)}, 250);
}
}