c#项目中从socketIO返回

本文关键字:socketIO 返回 项目 | 更新日期: 2023-09-27 18:01:15

我有这个代码从服务器接收一些数据。日志内套接字。On给出正确的数据,但返回时给出0。我不能在Socket.on.

public int GetInfor(string userID)
{
    int result = 0;
    socket.On("data" , (SocketIOEvent e) => {
        formData data= jss.Deserialize<formData>(string.Format("{0}", e.data));
        if (data.err) 
            result = Int32.Parse(data.Infor);
        else result = -1;
        Debug.Log (result);
    });
    Debug.Log (result);
    return result;
}

c#项目中从socketIO返回

我认为这种情况发生,因为你的方法返回的结果被设置为0直接没有等待接收任何事件。

这里有一个简单的解决方案:

public void GetInfor(string userID, Action<int> resultAction)
{
    int result = 0;
    socket.On("data" , (SocketIOEvent e) => {
        formData data= jss.Deserialize<formData>(string.Format("{0}", e.data));
        if (data.err) 
            result = Int32.Parse(data.Infor);
        else 
            result = -1;
        resultAction.Invoke(result); // or just simplt resultAction(result);
    });
}
使用

this.GetInfor("exampleUserId", result =>
{
    // do something with result
});