我正在使用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();
        [email protected] = "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);
        }
    }
}

最佳答案

使用

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


它应该可以解决问题

关于c# - 无法在WebSocket客户端中接收消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19380776/

10-08 21:40