1

I am pretty new to C#.

In Java, we can read the whole String from an InputStream of a WebSocket.
For example:

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

and so on...

Is it possible to do the same thing in C#, because the only possible way I found so far is to read bytes?

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

If there is no workaround, and we can only read single bytes in C#, how can I determine if the user have pressed the ENTER button (it would mean that the command is finished, and I can process it on the server-side)?

haldo
  • 14,512
  • 5
  • 46
  • 52
Abraham
  • 185
  • 1
  • 10
  • I compared the incoming byte value to 10 or 13, which seems to work. But I don't believe that this is the only way for us to get the whole commands from the user. – Abraham Mar 28 '20 at 21:39

1 Answers1

0

To read a line (i.e. a string followed by "\r" and/or "\n"), use StreamReader.ReadLine:

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

or its asynchronous equivalent, StreamReader.ReadLineAsync:

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

From the 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").

JeremyTCD
  • 695
  • 1
  • 6
  • 11