我正在使用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);
}
}
}
使用
Task.Delay(300) //instead of Thread.Sleep(2000)
它应该可以解决问题
我不熟悉websocket4net,但它可能是在同一线程上运行并且Thread.Sleep
阻止客户端接收回复。
也有可能是在Console.ReadLine();
阻止执行时回复,因此它没有到达Client_MessageReceived
。
第三种选择是答复的内容为空。在这种情况下,WebSocket 将不会触发该事件。我说的是,基于查看此处WebSocket
的代码:http://websocket4net.codeplex.com/SourceControl/latest#WebSocket4Net/WebSocket.cs
我参加聚会很晚了,但刚刚在 WebSocket4Net 上遇到了同样的问题。
github上提出了一个问题,可以解释为什么_send消息永远不会被发送:https://github.com/kerryjiang/WebSocket4Net/issues/170
这在发送多个连接请求时为我显现出来。每个请求都会在发送其他请求之前等待确认,当然,最终确认永远不会到达并阻止应用程序。 到目前为止,唯一有效的方法是在发送之前进行Thread.Sleep调用。