【问题标题】:Read whole Strings from WebSocket Stream in C# [duplicate]从 C# 中的 WebSocket 流中读取整个字符串 [重复]
【发布时间】:2020-03-28 21:27:12
【问题描述】:

我对 C# 很陌生。

在 Java 中,我们可以从 WebSocket 的 InputStream 中读取整个字符串。
例如:

dis = new DataInputStream(clientSocket.getInputStream());
String command = dis.readUTF();

等等……

是否可以在 C# 中做同样的事情,因为到目前为止我发现的唯一可能的方法是读取字节?

Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);

如果没有解决方法,并且我们只能读取 C# 中的单个字节,我如何确定用户是否按下了 ENTER 按钮(这意味着命令已完成,我可以在服务器上处理它-边)?

【问题讨论】:

  • 我将传入的字节值与 10 或 13 进行了比较,这似乎可行。但我不认为这是我们从用户那里获取全部命令的唯一方法。

标签: c# websocket client-server


【解决方案1】:

要读取一行(即后面跟着“\r”和/或“\n”的字符串),请使用StreamReader.ReadLine

string command;
using (StreamReader sr = new StreamReader(clientSocket.getInputStream())
{
    command = sr.ReadLine();
}

或其异步等效项StreamReader.ReadLineAsync

string command;
using (StreamReader sr = new StreamReader(clientSocket.getInputStream())
{
    command = await sr.ReadLineAsync();
}

来自documentationStreamReader.ReadLine

从当前流中读取一行字符并将数据作为字符串返回。
...
行定义为字符序列后跟换行符 ("\n")、回车符 ("\r") 或回车符后紧跟换行符 ("\r\n")。

【讨论】:

  • 谢谢你,杰里米!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 2017-04-01
  • 2018-02-05
相关资源
最近更新 更多