Introduced
Re-imagine the Windows 8 Store Apps Communication
Socket-tcp Demo
Socket-Implements a custom HTTP server
SOCKET-UDP Demo
Example
1, Demo socket TCP Application (this example is to do both server and client)
Communication/socket/tcpdemo.xaml
<page x:class= "XamlDemo.Communication.Socket.TcpDemo" xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/pre Sentation "xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "xmlns:local=" using: XamlDemo.Communication.Socket "xmlns:d=" http://schemas.microsoft.com/expression/blend/2008 "xmlns:mc=" http:// schemas.openxmlformats.org/markup-compatibility/2006 "mc:ignorable=" D "> <grid background=" Transparent "&
Gt
<stackpanel margin= "0 0 0" orientation= "horizontal" > <StackPanel>
<button name= "Btnstartlistener" content= "Start a Socket listener" click= "Btnstartlistener_click"/> <button name= "Btnconnectlistener" content= "connect to the socket listener" click= "Btnconnectlistener_click" Margin = "0 0 0"/> <button name= "btnsenddata" content= "Send Data" click= "Btnsenddata_click" margin= "0 10 0 0 "/> <button name=" BTNclosesocket "content=" Close server socket and client socket click= "Btnclosesocket_click" margin= "0 0 0"/> </StackPanel> <textblock name= "lblmsg" fontsize= "14.667" textwrapping= "Wrap" Ma rgin= "0 0 0"/> </StackPanel> </Grid> </Page>
Communication/socket/tcpdemo.xaml.cs
* * Demo Socket TCP Application (this example is both server and client) * * Through the Streamsocketlistener implementation of TCP Communication Server socket monitoring * through the Streamsocket implementation of TCP Pass Client Socket * * Note: Need to add configuration in Package.appxmanifest <capability name= "Privatenetworkclientserver"/> * * usi
Ng System;
Using Windows.networking;
Using Windows.Networking.Sockets;
Using Windows.Storage.Streams;
Using Windows.UI.Core;
Using Windows.UI.Xaml;
Using Windows.UI.Xaml.Controls;
Namespace XamlDemo.Communication.Socket {public sealed partial class Tcpdemo:page {///<summary>
Server socket///</summary> private Streamsocketlistener _listener;
<summary>///Client Socket///</summary> private streamsocket _client; <summary>///datawriter///</summary> private DataWriter _writer When the client sends data to the server
; Public Tcpdemo () {this.
InitializeComponent ();
}
Start a socket listener on the server side private async void Btnstartlistener_click (object sender, RoutedEventArgs e)
{//Instantiate a socket listener object _listener = new Streamsocketlistener (); Listens for event _listener that is triggered after a connection is received.
Connectionreceived + = _listener_connectionreceived; try {//start socket listening await _listener on the specified port.
Bindservicenameasync ("2211");
Lblmsg.text + = "has started socket (TCP) listening on the 2211 port of this machine";
Lblmsg.text + = Environment.NewLine; The catch (Exception ex) {socketerrorstatus errstatus = Socketerror.getstatus (ex.
HResult);
Lblmsg.text + = "Errstatus:" + errstatus.tostring ();
Lblmsg.text + = Environment.NewLine; Lblmsg.text = ex.
ToString ();
Lblmsg.text + = Environment.NewLine; }//Socket SupervisorListen to receive a connection after async void _listener_connectionreceived (Streamsocketlistener sender, streamsocketlistenerconnectionrecei Vedeventargs args) {//instantiate a DataReader for reading data DataReader reader = new DataReader (args.
Socket.inputstream); Await this. Dispatcher.runasync (Coredispatcherpriority.normal, () => {lblmsg.text = = "Server received from:" + AR Gs. Socket.Information.RemoteHostName.RawName + ":" + args.
Socket.Information.RemotePort + "socket connection";
Lblmsg.text + = Environment.NewLine;
}); try {while (true) {//Custom Protocol (HEADER|BODY): The first 4 bytes represent the length of the actual data, After the actual data is a string data//Read header uint Sizefieldcount = await reader.
LoadAsync (sizeof (UINT));
if (sizefieldcount!= sizeof (UINT)) {//the socket closes before obtaining the legal data Return //Read body uint stringlength = reader.
ReadUInt32 (); UINT Actualstringlength = await reader.
LoadAsync (stringlength);
if (stringlength!= actualstringlength) {//Before obtaining legal data, the socket is closed
Return } await this.
Dispatcher.runasync (Coredispatcherpriority.normal, () => { Displays the data sent over by the client Lblmsg.text + + "received data:" + reader.
ReadString (actualstringlength);
Lblmsg.text + = Environment.NewLine;
}); } catch (Exception ex) {var ignore = this. Dispatcher.runasync (Coredispatcherpriority.normal, () => {socketerrorstatus Errsta Tus =Socketerror.getstatus (ex.
HResult);
Lblmsg.text + = "Errstatus:" + errstatus.tostring ();
Lblmsg.text + = Environment.NewLine; Lblmsg.text = ex.
ToString ();
Lblmsg.text + = Environment.NewLine;
}); }//Create a client socket and connect to the server socket private async void Btnconnectlistener_click (Object Sende
R, RoutedEventArgs e) {HostName HostName;
try {hostName = new HostName ("127.0.0.1"); catch (Exception ex) {lblmsg.text = ex.
ToString ();
Lblmsg.text + = Environment.NewLine;
Return
//Instantiate a client socket object _client = new Streamsocket (); try {//Connect to the specified service-side socket await _client.
ConnectAsync (HostName, "2211"); Lblmsg.text + + "has been connected to the 127.0.0.1:2211";
Lblmsg.text + = Environment.NewLine; The catch (Exception ex) {socketerrorstatus errstatus = Socketerror.getstatus (ex.
HResult);
Lblmsg.text + = "Errstatus:" + errstatus.tostring ();
Lblmsg.text + = Environment.NewLine; Lblmsg.text = ex.
ToString ();
Lblmsg.text + = Environment.NewLine; }//Send a string data from client socket to the service socket private async void Btnsenddata_click (object sender, R Outedeventargs e) {//Instantiate a datawriter for sending data if (_writer = null) _write R = new DataWriter (_client.
OutputStream); Custom Protocol (Header|body): The first 4 bytes represent the length of the actual data, followed by the actual data string data = "Hello Webabcd" + DateTime.Now.ToStri
Ng ("Hh:mm:ss"); _writer. WriteUInt32 (_writer. MeasureString (data)); Write header data
_writer. WriteString (data); Write body Data try {//Send data await _writer.
Storeasync ();
Lblmsg.text + = "Data sent:" + date;
Lblmsg.text + = Environment.NewLine; The catch (Exception ex) {socketerrorstatus errstatus = Socketerror.getstatus (ex.
HResult);
Lblmsg.text + = "Errstatus:" + errstatus.tostring ();
Lblmsg.text + = Environment.NewLine; Lblmsg.text = ex.
ToString ();
Lblmsg.text + = Environment.NewLine; }///Close client socket and service socket private void Btnclosesocket_click (object sender, Routedeventa RGS e) {try {_writer. Detachstream (); Separate the datawriter associated with the Stream _writer.
Dispose (); _client.
Dispose (); _listener.
Dispose (); Lblmsg.text + = "Server socket and client socket are closed";
Lblmsg.text + = Environment.NewLine; catch (Exception ex) {lblmsg.text = ex.
ToString ();
Lblmsg.text + = Environment.NewLine; }
}
}
}