WinRT支持:
- StreamSocket,TCP 客户端
- StreamSocketListener,TCP 服务端
- StreamWebSocket,WebSocket客户端
- MessageWebSocket,WebSocket客户端
- DatagramSocket,UDP 的端
Socket定位远程机器:
public sealed class HostName : IStringable {
// Constructor
public HostName(String hostName); // e.g. "server", "192.168.1.125", etc.
// Read-only information about the host name:
public HostNameType Type { get; } // DomainName, Ipv4, Ipv6, Bluetooth
public String RawName { get; } // Same value passed to constructor
public String DisplayName { get; } // String that can be shown to a user
public String CanonicalName { get; } // String that can be used by the app's code
public IPInformation IPInformation { get; } // NetworkAdapter info for an Ipv4/Ipv6 address
// Methods to compare canonical hostnames with one another:
public Boolean IsEqual(HostName hostName);
public static Int32 Compare(String value1, String value2);
}
StreamSocket:
public sealed class StreamSocket : IDisposable {
public StreamSocket();
// OPTIONAL: Modify connection (keep alive, outbound buffer size, QoS)
// before calling ConnectAsync
public StreamSocketControl Control { get; }
// Returns connection read-only information (bandwidth, host/service names, timings)
public StreamSocketInformation Information { get; }
// Connect to a service on a remote machine (other overloads not shown here)
public IAsyncAction ConnectAsync(HostName remoteHostName, String remoteServiceName,
SocketProtectionLevel protectionLevel);
// After calling ConnectAsync, the app uses these to read & write data
public IInputStream InputStream { get; }
public IOutputStream OutputStream { get; }
// Upgrade a connected socket to use SSL
public IAsyncAction UpgradeToSslAsync(
SocketProtectionLevel protectionLevel, HostName validationHostName);
public void Dispose(); // Close the socket
}
连接的例子:
private async Task TcpClientAsync() {
using (StreamSocket socket = new StreamSocket())
using (DataWriter dw = new DataWriter(socket.OutputStream))
using (DataReader dr = new DataReader(socket.InputStream)) {
// Connect to the remote server:
await socket.ConnectAsync(new HostName("localhost"), “8080”);
// Send message header (UInt32) and message bytes to server:
Byte[] messageData = new Byte[] { 1, 2 };
dw.WriteUInt32((UInt32)messageData.Length);
dw.WriteBytes(messageData);
await dw.StoreAsync();
// Read UInt32 response from server:
await dr.LoadAsync(sizeof(Int32));
Int32 sum = dr.ReadInt32();
}
}
StreamSocketListener:
public sealed class StreamSocketListener : IDisposable {
public StreamSocketListener();
// OPTIONAL: Modify connection (QoS) before calling BindXxxAsync
public StreamSocketListenerControl Control { get; }
// Returns read-only information about the connection (local port)
public StreamSocketListenerInformation Information { get; }
// This event is raised whenever a client connects to this socket listener
public event TypedEventHandler<StreamSocketListener,
StreamSocketListenerConnectionReceivedEventArgs> ConnectionReceived;
// Start listening on local IP addresses of all NICs
// If localServiceName is "", system picks port
public IAsyncAction BindServiceNameAsync(String localServiceName);
// Start listening on the hostname/IP address and service name specified.
// If localHostName is 'null', local IP is used; if localServiceName is "", OS picks port.
public IAsyncAction BindEndpointAsync(HostName localHostName, String localServiceName);
public void Dispose(); // Close the socket
}
接收消息:
public sealed class StreamSocketListenerConnectionReceivedEventArgs {
// Returns a StreamSocket created by the client connection
// Use its IInputStream and IOutputStream to talk to the client
public StreamSocket Socket { get; }
}
例子:
// NOTE: Don't let the returned StreamSocketListener be garbage collected
// until you no longer want to accept connections
private async Task<StreamSocketListener> StartTcpServiceAsync(String localServiceName) {
var tcpService = new StreamSocketListener();
// You must register handlers before calling BindXxxAsync
tcpService.ConnectionReceived += OnConnectionReceived;
await tcpService.BindServiceNameAsync(localServiceName); // Listen on desired port
return tcpService;
}
private async void OnClientConnectionReceivedAsync(StreamSocketListener listener,
StreamSocketListenerConnectionReceivedEventArgs e) {
using (StreamSocket client = e.Socket)
using (DataReader dr = new DataReader(e.Socket.InputStream))
using (DataWriter dw = new DataWriter(e.Socket.OutputStream)) {
// Read request header from client:
await dr.LoadAsync(sizeof(Int32));
UInt32 messageLength = dr.ReadUInt32();
// Read request data from client:
await dr.LoadAsync(messageLength);
Byte[] bytes = new Byte[messageLength];
dr.ReadBytes(bytes);
Int32 sum = bytes.Sum(number => number); // Calculate response
// Send response to client:
dw.WriteInt32(sum);
await dw.StoreAsync(); // Required to send the response back to the client
}
}
DatagramSocket,UDP通信:
// NOTE: Don't let the returned DatagramSocket be garbage collected
// until you no longer want to accept messages
private async Task<DatagramSocket> StartMulticastListenerAsync(String localServiceName) {
DatagramSocket multicastListener = new DatagramSocket();
// You must register handlers before calling BindXxxAsync
multicastListener.MessageReceived += OnMulticastListenerMessageReceived;
await multicastListener.BindServiceNameAsync(localServiceName); // Listen on desired port
// IPv4 multicast IP addresses: 224.0.0.0 to 239.255.255.255
HostName hostname = new HostName("224.168.100.2"); // Pick a multicast IP address
multicastListener.JoinMulticastGroup(hostname); // Join socket to the multicast IP address
return multicastListener;
}