I am using StreamSocket
to connect to a socket server and I use a infinite loop to read data. Each piece of data ends with '\n\n'
. The snippet is shown below. However, I can't know whether the socket is still alive, and every time the server shuts down the connection, ReadAsync()
throws exception. How to be notified when the connection is closed?
public async Task<string> ReadData() {
StreamReader reader = new StreamReader(socket.InputStream.AsStreamForRead());
char[] ch = new char[65536];
int i = 0;
while (IsConnected) {
await reader.ReadAsync(ch, i++, 1);
if (i > 1 && ch[i - 1] == '\n' && ch[i - 2] == '\n') break;
}
return new StringBuilder().Append(ch, 0, i - 2).ToString();
}