0

I need WebSocket code for implement structure of my client. I will create WebSocket server for my client with receive by client from ex: binance websocket

Just part of connect to binance websocket need implement.

ASP.NET Core 5 C#

private async Task Echo(HttpContext context, WebSocket webSocket)
{
    var buffer = new byte[1024 * 4];
    WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
    while (!result.CloseStatus.HasValue)
    {
        await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

        result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
    }
    await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
2
  • we need to see a fully reproducible example and the error you are getting Commented Mar 7, 2021 at 17:41
  • this is my code in setup basic send message on websocket just i need make sure we can connect websocket server to another one ? and my client recieve master websocket WS A > WS B > Client Commented Mar 7, 2021 at 23:01

1 Answer 1

1

I did something like that. I created 2 WebSocket servers, one acting as a proxy to the other. You can check it out, maybe it works for you or at least you can find some answers there. It is a bit disordered because I did it as a research, so ask me if you need more info.

https://github.com/RenanDiaz/WebSockets

public override async Task OnConnected(WebSocket socket)
{
    await base.OnConnected(socket);
    if (_client == null)
    {
        _client = new ClientWebSocket();
        await _client.ConnectAsync(new Uri("ws://localhost:5001/chat"), CancellationToken.None);
        var thread = new Thread(new ThreadStart(ReceiveMessageFromAPIServer));
        thread.Start();
    }
}

private async void ReceiveMessageFromAPIServer()
{
    var buffer = new byte[1024 * 4];
    while (_client != null)
    {
        var result = await _client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        if (result.MessageType == WebSocketMessageType.Close)
        {
            await _client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
            break;
        }
        var messageString = Encoding.UTF8.GetString(buffer, 0, result.Count);
        var message = JsonConvert.DeserializeObject<IncomingAPIServerMessage>(messageString);
        await SendMessageToAll(message);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.