Websocket4Net Send Multiple messages

8.8k Views Asked by At

I'm having a problem using WebSocket4Net library.

I have the event websocket_opened and when this event is raised on open if I don't send any messages I have an Exception

System.Exception : You must send data by websocket after websocket is opened

After I send this message I can't send any other messages. I execute the send command but I have no exceptions and it isn't working and If I check the state the websocket is open

If I close the Socket on the opened event and open it again in the closed_event I can send another message without problems.

So, if I want to send multiple messages I have to disconnect after sending a message and reconnect again to send the next message.

private static void websocket_Opened(object sender, EventArgs e)
{
    websocket.Send(msg);
    websocket.Close();
}

private static void websocket_Closed(object sender, EventArgs e)
{
    websocket.Open();
}

Is this normal? Can you help me with this please?

2

There are 2 best solutions below

0
On

I had a similar questions when I first time used WebSocket4Net. A good thing about this library that it has a repository on github with many examples of use (tests). These tests was very helpful for me to understand how it should work.

UPDATE: I saw Fred's comment below and I think I really need to add an example. So here is it, I've used this api:

using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocket4Net;

namespace TestProj
{
  public class WebSocketTest
  {
    static string webSocketUri = "wss://ws.binaryws.com/websockets/v3?app_id=1089";

    static void Main(string[] args)
    {
        var socketManager = new WebSocketManager(webSocketUri);

        socketManager.Send("{\"time\": 1}");
        socketManager.Send("{\"ping\": 1}");
        socketManager.Close();

        Console.WriteLine("Console can be closed...");
        Console.ReadLine();
    }
}
public class WebSocketManager
{
    private AutoResetEvent messageReceiveEvent = new AutoResetEvent(false);
    private string lastMessageReceived;
    private WebSocket webSocket;

    public WebSocketManager(string webSocketUri)
    {
        Console.WriteLine("Initializing websocket. Uri: " + webSocketUri);
        webSocket = new WebSocket(webSocketUri);
        webSocket.Opened += new EventHandler(websocket_Opened);
        webSocket.Closed += new EventHandler(websocket_Closed);
        webSocket.Error += new EventHandler<ErrorEventArgs>(websocket_Error);
        webSocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);

        webSocket.Open();
        while (webSocket.State == WebSocketState.Connecting) { };   // by default webSocket4Net has AutoSendPing=true, 
                                                                    // so we need to wait until connection established
        if (webSocket.State != WebSocketState.Open)
        {
            throw new Exception("Connection is not opened.");
        }
    }

    public string Send(string data)
    {
        Console.WriteLine("Client wants to send data:");
        Console.WriteLine(data);

        webSocket.Send(data);
        if (!messageReceiveEvent.WaitOne(5000))                         // waiting for the response with 5 secs timeout
            Console.WriteLine("Cannot receive the response. Timeout.");

        return lastMessageReceived;
    }

    public void Close()
    {
        Console.WriteLine("Closing websocket...");
        webSocket.Close();
    }

    private void websocket_Opened(object sender, EventArgs e)
    {
        Console.WriteLine("Websocket is opened.");
    }
    private void websocket_Error(object sender, ErrorEventArgs e)
    {
        Console.WriteLine(e.Exception.Message);
    }
    private void websocket_Closed(object sender, EventArgs e)
    {
        Console.WriteLine("Websocket is closed.");
    }

    private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
    {
        Console.WriteLine("Message received: " + e.Message);
        lastMessageReceived = e.Message;
        messageReceiveEvent.Set();
    }
  }
}
0
On

i think that this will resolve your problem

websocket.Open();
private static void websocket_Opened(object sender, EventArgs e)
{
    websocket.Send(msg); 
    websocket.Close(); 
}

private static void websocket_Closed(object sender, EventArgs e)
{
    //DO SOMETHINGS
}