TCP in Windows Runtime(运行时) GIS

Windows.Networking.Sockets namespace

As with the .NET implementation, there are two primary classes to handle server and client roles. In WinRT, these are StreamSocketListener and StreamSocket.

The following method starts a server on port 51111, and waits for a client to connect,It then reads a single message comprising a length-prefixed string:

async void Server()
{
var listener = new StreamSocketListener();
listener.ConnectionReceived += async (sender, args) =>
{
using (StreamSocket socket = args.Socket)
{
var reader = new DataReader (socket.InputStream);
await reader.LoadAsync (4);
uint length = reader.ReadUInt32();
await reader.LoadAsync (length);
Debug.WriteLine (reader.ReadString (length));
}
listener.Dispose(); // Close listener after one message.
};
await listener.BindServiceNameAsync ("51111");
}

In this example, we used a WinRT type called DataReader (in Windows.Networking)to read from the input stream, rather than converting to a .NET Stream object and
using a BinaryReader. DataReader is rather like BinaryReader except that it supports asynchrony. The LoadAsync method asynchronously reads a specified number of
bytes into an internal buffer, which then allows you to call methods such as Read UInt32 or ReadString. The idea is that if you wanted to, say, read 1000 integers in a
row, you’d first call LoadAsync with a value of 4000, and then ReadInt32 1000 times in a loop. This avoids the overhead of calling asynchronous operations in a loop (as each asynchronous operation incurs a small overhead).

The StreamSocket object that we obtained from awaiting AcceptAsync has separate input and output streams. So, to write a message back, we’d use the socket’s OutputStream.

We can illustrate the use of OutputStream and DataWriter with the corresponding client code:

async void Client()
{
using (var socket = new StreamSocket())
{
await socket.ConnectAsync (new HostName ("localhost"), "51111",
SocketProtectionLevel.PlainSocket);
var writer = new DataWriter (socket.OutputStream);
string message = "Hello!";
uint length = (uint) Encoding.UTF8.GetByteCount (message);
writer.WriteUInt32 (length);
writer.WriteString (message);
await writer.StoreAsync();
}
}

We start by instantiating a StreamSocket directly, then call ConnectAsync with the host name and port. (You can pass either a DNS name or an IP address string into
HostName’s constructor.) By specifying SocketProtectionLevel.Ssl, you can request SSL encryption (if configured on the server).
Again, we used a WinRT DataWriter rather than a .NET BinaryWriter, and wrote the length of the string (measured in bytes rather than characters), followed by the
string itself which is UTF-8 encoded. Finally, we called StoreAsync which writes the buffer to the backing stream, and closed the socket.

原文地址:https://www.cnblogs.com/gisbeginner/p/2671641.html