在 C# 中从 WebSocket Stream 中读取整个字符串
Read whole Strings from WebSocket Stream in C#
我是 C# 的新手。
在Java中,我们可以从WebSocket 的InputStream 中读取整个String。
例如:
dis = new DataInputStream(clientSocket.getInputStream());
String command = dis.readUTF();
等等...
是否可以在 C# 中做同样的事情,因为到目前为止我发现的唯一可能的方法是读取字节?
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
如果没有解决方法,我们只能在C#中读取单个字节,我如何确定用户是否按下了ENTER按钮(这意味着命令完成,我可以在服务器端)?
要读取一行(即字符串后跟“\r”and/or“\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();
}
来自 documentation for StreamReader.ReadLine
:
Reads a line of characters from the current stream and returns the data as a string.
...
A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n").
我是 C# 的新手。
在Java中,我们可以从WebSocket 的InputStream 中读取整个String。
例如:
dis = new DataInputStream(clientSocket.getInputStream());
String command = dis.readUTF();
等等...
是否可以在 C# 中做同样的事情,因为到目前为止我发现的唯一可能的方法是读取字节?
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
如果没有解决方法,我们只能在C#中读取单个字节,我如何确定用户是否按下了ENTER按钮(这意味着命令完成,我可以在服务器端)?
要读取一行(即字符串后跟“\r”and/or“\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();
}
来自 documentation for StreamReader.ReadLine
:
Reads a line of characters from the current stream and returns the data as a string.
...
A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n").