C#中KotlinWebSocketSession对象的等价物是什么?

xdnvmnnf  于 2022-11-11  发布在  C#
关注(0)|答案(1)|浏览(143)

几个月来,我一直在使用ktor框架创建通过webSockets公开rest调用和通信的服务器。目前,我一直使用使用Kotlin作为编程语言的客户端(* 或Android应用程序,或App Desktop*)。
具体地说,我有一个用HttpClient对象注入的类(* 来自文档=执行HTTP请求的异步客户端 )。
在这个类中,我有4个方法:
1.启动会话:示例化WebSocketSession对象(
表示两个对等方之间的Web套接字会话 *)
1.发送帧
1.接收帧
1.关闭会话
Ktor中,我的类看起来很像这样:

class WebSocketServiceImpl(
    private val client: HttpClient
){

private var socket: WebSocketSession? = null

//1)
suspend fun initSession(username: String): Resource<Unit>{
   socket = client.webSocketSession {
                url("ws://xxx.xxx.xxx.xxx:xxxx/myRoute?username=$username")
}

//2)
suspend fun send(myObj: MyObj) {
        try {
            val myObjSerialized = Json.encodeToString(myObj)
            socket?.send(Frame.Text(myObjSerialized ))
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

//3)
fun observePrintableMessages(): Flow<MyObj> {
        return try {
            socket?.incoming
                ?.receiveAsFlow()
                ?.filter { it is Frame.Text }
                ?.map {
                    val myObjString = (it as? Frame.Text)?.readText() ?: ""
                    val printableMessageDto = Json.decodeFromString<MyObj>(myObjString)
                } ?: flow { }
        } catch (e: Exception) {
            e.printStackTrace()
            flow { }
        }
    }

//4)
suspend fun closeSession() {
        socket?.close()
    }

}

相反,我从C#文档中找到了有关如何使用客户端WebSockets的以下示例:

//1)
const exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");

//2)
exampleSocket.send("Here's some text that the server is urgently awaiting!");

//3)
exampleSocket.onmessage = (event) => {
  console.log(event.data);
}

//4)
exampleSocket.close();

承认而不是承认我在C#中找到的方法确实有效,使C#中使用的WebSocket对象等效于Kotlin中的WebSocketSession对象对我来说是否足够?:

public void initSession(string username)
{
   exampleSocket = new WebSocket($"wss://www.example.com/socketserver?username={username}", "");
}

或者是要使用的其他类型的对象?
如果你不知道答案,你不需要投反对票,你可以继续前进。

d4so4syb

d4so4syb1#

我使用了NuGet上的WebSocket.Client库(由MariuszKotas编写)

public class WebSocketService : IWebSocketService
{

    public event EventHandler<MessageReceivedEventArgs> MessageReceived;
    private void FireMessageReceivedEvent(Message message) => MessageReceived?.Invoke(this, new MessageReceivedEventArgs(message));

    public string Url { get => "ws://192.168.1.202:8082/chat-socket"; }

    private WebsocketClient webSocketClient;

    public async Task<SessionResoult> InitSession(string username)
    {
        string usernameSession = $"?username={username}";
        string urlWithUsername = $"{Url}{usernameSession}";
        try
        {
            webSocketClient = new WebsocketClient(new Uri(urlWithUsername));
            await webSocketClient.Start();
            if (webSocketClient.IsRunning)
            {
                SubscribeNewMessages();
                return new SessionResoult.Success();
            }
            else
            {
                return new SessionResoult.Error("webSocketClient is not running");
            }
        }
        catch(Exception ex)
        {
            return new SessionResoult.Error(ex.Message);
        }

    }

    private void SubscribeNewMessages()
    {
        webSocketClient.MessageReceived.Subscribe(m =>
        {
            MessageDto message = JsonConvert.DeserializeObject<MessageDto>(m.Text);
            FireMessageReceivedEvent(message.ToMessage());
        });
    }

    public async Task SendMessageAsync(string message)
    {

        await Task.Run(() => webSocketClient.Send(message));
    }

    public void CloseSession()
    {
        webSocketClient.Dispose();
    }

}

在代码中,有趣的部分是:

**1)**初始化WebsocketClient对象
**2)**接收消息的订阅(Start() 方法初始化后立即执行)
**3)**消息订阅的观察-〉*webSocketClient.消息接收.订阅 *
**4)*与消息观察相关联的事件的“触发”-〉 触发消息接收事件 *
**5)**使用该类的人必须订阅后者的事件-〉

消息发送方:发送方:消息接收方:消息发送方:消息接收方:消息发送方:消息接收方:消息发送方:消息接收方:消息发送方:消息接收方:消息发送方:消息接收方:消息发送方:消息接收方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:消息发送方:};*

MessageReceivedEventArgs-〉描述事件参数的类
SessionResoult-〉类类似于枚举,但可以传递字符串或不基于它是哪个子类

相关问题