Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
webSocket.send() inside webSocket.onopen always fails

I'm starting with WebSockets and, to try things off, I built a minuscule WebSocket server in C# (using WebSocketSharp) and an html as a client to connect to it.

On the client I have this code:

    const webSocket = new WebSocket("ws://localhost:51036/test");

    webSocket.onopen = e => {
        webSocket.send("hello :D");
        console.log("Socket connection opened!");
    }

This send() call never works — it sometimes result in an exception in the C# server, most other times it is just ignored as if nothing was ever received on the server's end. However, any send() I call afterwards (e.g. with a button) works fine, and send() inside onopen also works fine if I place it inside a timeout of just 200ms. If I don't call any send() onopen, and just call it later via a button, it always works fine (so it's not a 'first call always fails' issue).

On the C# side, the code is very simple:

public class TestWS : WebSocketBehavior {
    protected override void OnMessage (MessageEventArgs e) {
        System.Diagnostics.Debug.WriteLine($"Client message: {e.Data}");
        Send($"String length: {e.Data.Length} [msg received: {e.Data}]");
    }
}

public static class Sockets {
    public const string SERVER_ROUTE = "ws://localhost:51036";

    private static WebSocketServer socket;

    public static void Start () {
        socket = new WebSocketServer(SERVER_ROUTE);
        socket.AddWebSocketService<TestWS>("/test");

        socket.Start();
        System.Diagnostics.Debug.WriteLine($"Server started on {SERVER_ROUTE}");
    }

    public static void Stop () {
        socket.Stop();
    }
}

The exception in question is this one:

2021-09-06 19:59:06|Fatal|WebSocket.<startReceiving>b__175_2:0|WebSocketSharp.WebSocketException: The header of a frame cannot be read from the stream.
                         at WebSocketSharp.WebSocketFrame.processHeader(Byte[] header)
                         at WebSocketSharp.WebSocketFrame.<>c__DisplayClass73_0.<readHeaderAsync>b__0(Byte[] bytes)
                         at WebSocketSharp.Ext.<>c__DisplayClass55_0.<ReadBytesAsync>b__0(IAsyncResult ar)
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda