My task involves creating a .NET WebSocket server using TcpClient and NetworkStream to communicate with a JavaScript client. The client initiates the connection and requests specific actions from the server, which then generates responses. Previously, these responses were short JSON strings sent back to the client successfully.
However, when the requirement arose to send larger string responses, such as base64 encoded images exceeding 200k bytes, the client stopped receiving responses and the onmessage event was not triggered. Sending shorter JSON data worked fine, indicating an issue specifically with larger data.
Here is an example of sending large data:
https://i.sstatic.net/MIWQs.png
And here is an example of sending simple data:
https://i.sstatic.net/D0fIt.png
On the client side, I have stripped down the code to remove any unrelated components, but the behavior remained consistent:
try{
ws = new WebSocket("ws://127.0.0.1:8282");
ws.binaryType = "arraybuffer";
}
catch(err){
debugger;
document.getElementById("message").innerHTML = "Not Connected! " + err;
};
ws.onopen = function () {
var jsonRequest = '{"action" : "START_STREAM","timeout" : 20}';
ws.send("START_STREAM");
};
As for the server-side code, after generating the response (which includes a plain string with base64 encoded image), the following method is executed:
Byte[] frame = CreateFrameFromString(serverResponse);
networkStream.Write(frame, 0, frame.Count());
networkStream.Flush();
clientSocket.Close();
clientSocket = ServerListener.AcceptTcpClient();
networkStream = clientSocket.GetStream();
The initialization code for the server thread is as follows:
ServerListener.Start();
clientSocket = ServerListener.AcceptTcpClient();
NetworkStream networkStream = clientSocket.GetStream();
while (true)
{
if (!networkStream.DataAvailable)
...regular loop/server stuff/handshake etc.
Below is the method 'CreateFrameFromString' that handles framing the message before sending it:
private static byte[] CreateFrameFromString(string message, Opcode opcode = Opcode.Text)
{
var payload = Encoding.UTF8.GetBytes(message);
// Frame creation logic...
return frame;
}
Upon testing, I found that I could successfully send responses with up to 4250 characters without any modifications to the setup. However, once I exceeded that limit, the responses started disappearing. Are there any protocol or buffer size considerations that I might be missing?