I have an application that I am writing for Windows 8 / WinRT that uses the StreamSocket API to stream connections to the server. That is, the server transfers data to the client, sometimes with meta tags, and can disconnect at any time.
The problem I am facing is that I have no idea how to determine when the server was down. It seems that there are no events or properties in the StreamSocket class, be it its input or output streams or the DataReader / DataWriter classes that have anything to do with the connection status.
In addition, the DataReader ReadAsync method is not interrupted after the server side disconnects from the client. Instead, the operation succeeds, as far as I can tell, and the data that it fills in its buffer is just the last thing the server sent to it (i.e., it didn’t clear its internal buffer, although I see that it “consumes” ", buffer every time I call ReadByte). He does this for each subsequent call to ReadAsync - replenishing the buffer with what the server sent last before it was disconnected. Here is a simplified version of the code:
public async Task TestSocketConnectionAsync()
{
var socket = new StreamSocket();
await socket.ConnectAsync(new HostName(Host), Port.ToString(),
SocketProtectionLevel.PlainSocket);
var dr = new DataReader(socket.InputStream);
dr.InputStreamOptions = InputStreamOptions.Partial;
this.cts = new CancellationTokenSource();
this.listenerOperation = StartListeningAsync(dr, cts);
}
public async Task StartListeningAsync(DataReader dr, CancellationTokenSource cts)
{
var token = cts.Token;
while (true)
{
token.ThrowIfCancellationRequested();
var readOperation = dr.LoadAsync(1024);
var result = await readOperation;
if (result <= 0 || readOperation.Status != Windows.Foundation.AsyncStatus.Completed)
{
cts.Cancel();
}
else
{
while (dr.UnconsumedBufferLength > 0)
{
byte nextByte = dr.ReadByte();
}
}
}
}
source
share