无法在WebSocket客户端中接收消息

时间:2013-10-15 12:05:17

标签: c# websocket websocket4net

我使用websocket4net在C#中创建WebSocket客户端并与服务器通信。

我能够发送数据,但无法接收服务器发回的回复。根本没有触发Client_MessageReceived。我能在WireShark看到回复。

我使用的代码如下:

class CommandRPC
{
    public String jsonrpc;
    public String method;
    public Parameter @params;
    public String id;
}    

class Parameter
{
    public String cmd;
}

class Program
{
    static WebSocket Client;

    static CommandRPC command;

    static void Main(string[] args)
    {
        Client = new WebSocket("ws://10.131.35.32/DIAG");
        Client.Opened += new EventHandler(Client_Opened);
        Client.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(Client_Error);
        Client.Closed += new EventHandler(Client_Closed);
        Client.MessageReceived += new EventHandler<MessageReceivedEventArgs>(Client_MessageReceived);
        Client.DataReceived += new EventHandler<DataReceivedEventArgs>(Client_DataReceived);


        command = new CommandRPC();
        command.jsonrpc = "2.0";
        command.method = "SystemExec";
        command.@params = new Parameter();
        command.@params.cmd = "ls";
        command.id = "8302144";

        Client.Open();
        System.Threading.Thread.Sleep(2000);
        Console.WriteLine(Client.State);
        Console.ReadLine();
    }


    static void Client_DataReceived(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine("DATA received : " + e.Data);
    }

    static void Client_MessageReceived(object sender, MessageReceivedEventArgs e)
    {
        Console.WriteLine("Message received : " + e.Message);            
    }

    static void Client_Closed(object sender, EventArgs e)
    {
        Console.WriteLine("Websocket closed");
    }

    static void Client_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
    {
        Console.WriteLine("Error thrown trying to open websocket : " + e.Exception.Message);
    }

    static void Client_Opened(object sender, EventArgs e)
    {
        var json = new JavaScriptSerializer().Serialize(command);            
        Console.WriteLine("Websocket connection open.");

        for (int i = 1; i <= 2; i++)
        {
            Console.WriteLine("Sending Json: " + i.ToString());
            Client.Send(json);
            System.Threading.Thread.Sleep(500);
        }   
    }
}

3 个答案:

答案 0 :(得分:4)

使用

   Task.Delay(300) //instead of Thread.Sleep(2000)

它应该做的伎俩

答案 1 :(得分:2)

我对websocket4net并不熟悉,但可能是它在同一个线程上运行,Thread.Sleep阻止客户端收到回复。

Console.ReadLine();阻止执行时,回复也可能出现,因此无法到达Client_MessageReceived

第三种选择是答复的内容为空。在这种情况下,WebSocket不会触发事件。我的意思是基于查看WebSocket的代码:http://websocket4net.codeplex.com/SourceControl/latest#WebSocket4Net/WebSocket.cs

答案 2 :(得分:0)

我参加聚会很晚,但刚刚在 WebSocket4Net 上遇到了同样的问题。

github 上提出了一个问题,可以解释为什么 _send 消息永远不会被发送: https://github.com/kerryjiang/WebSocket4Net/issues/170

这在我发送多个连接请求时表现出来。每个请求都会在发送额外请求之前等待确认,当然,最终确认永远不会到达并阻止应用程序。到目前为止,唯一有效的是在发送之前调用 Thread.Sleep。