WinRT - TCP clients?
I am building an IRC client in the new WinRT (.NET 4.5
) framework for Windows 8 Metro applications.
However, I have some issues. I've already figured out that I need to use a StreamSocket
to read TCP data, but I may be doing something wrong.
The reason I believe this is because I am not receivi开发者_开发问答ng any data.
Below you see my code. I haven't been able to find any code samples on the web regarding this.
class IRCClient
{
private StreamSocket tcpClient;
public string Server = "holmes.freenode.net";
public int Port = 6665;
public IRCClient()
{
tcpClient = new StreamSocket();
}
public async void Connect()
{
await tcpClient.ConnectAsync(
new Windows.Networking.HostName(Server),
Port.ToString(),
SocketProtectionLevel.PlainSocket);
DataReader reader = new DataReader(tcpClient.InputStream);
string data = reader.ReadString(reader.UnconsumedBufferLength);
MessageDialog dialog = new MessageDialog(data);
}
}
Data is always an empty string following that code. Furthermore, UnconsumedBufferLength always returns 0.
How come?
You need to tell the DataReader
to read bytes from the stream before you interpret them (ReadString
just interprets the bytes already read).
So, if you want to read a string of 20 bytes, do this:
DataReader reader = new DataReader(tcpClient.InputStream);
await reader.LoadAsync(20);
string data = reader.ReadString(reader.UnconsumedBufferLength);
If you want to read a string up to 20 bytes, do this:
DataReader reader = new DataReader(tcpClient.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
await reader.LoadAsync(20);
string data = reader.ReadString(reader.UnconsumedBufferLength);
See this video for more info: http://channel9.msdn.com/Events/BUILD/BUILD2011/PLAT-580T
Note that DataReader
does not give you message boundaries; it's just a more convenient way of waiting for and reading binary data from a stream. You still need message framing.
精彩评论