问题描述
我在弄清楚这一点时遇到了一些麻烦。
我需要使用 WebSocketSharp 和客户端编写 API 服务器。我通过交换消息成功建立了连接,但是,我无法找到一种方法来正确实现这样的行为:
1) Client sends a message with request to the server and waits for a response
2) Server handles the request and response with another message
3) Client receives the response and handles the function
第 2) 点已经在服务器端完成,但由于以下原因,我很难实现第 1 点和第 3 点:当客户端向服务器发送消息时,它不会等待响应,而是立即跳到下一个代码执行。
我设法实现了一种半功能方式,这种方式做得很糟糕,并且可能会在很多方面出错(超时、延迟、要处理的多条消息等),例如,这就是我处理登录服务器的方式:
Class Connection {
private bool auth = false;
public string user,pwd;
WebSocket ws = new WebSocket("ws://localhost:1111");
public void Start() {
ws.OnMessage += Ws_OnMessage;
ws.Connect();
}
public void Ws_OnMessage(object sender,MessageEventArgs e) {
string[] decode = e.Data.Split(','); //splitting the server response
if (decode[0].Contains("auth") && decode[1].Contains("accepted")) { auth = true; } //handle request
}
public bool login()
{
ws.Send($"auth,{user},{pwd}"); //client send request to login to server
Thread.Sleep(3000); //wait response from server handled over Ws_onMessage
if (auth) { return true; } else { return false; } //check the response based on bool
}
}
这在“完美”的条件下是可行的,但我们都知道没有什么是完美的,这会导致许多失败。
我的问题是,如何正确实现这种行为?有没有合适的方法?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)