Windows 8 Store Apps(62)-通信:Socket TCP、Socket UDPを再想像
64928 ワード
[ソースのダウンロード]
Windows 8 Store Apps(62)-通信:Socket TCP、Socket UDPを再想像
作者:webabcd紹介Windows 8 Store Appsの再想像 通信 Socket-Tcp Demo Socket-カスタムhttp server を実現します。 Socket-Udp Demo 例1、socket tcpのアプリケーションをデモする(この例ではサービスとクライアントを両方行う)Communication/Socket/TcpDemo.xaml
Windows 8 Store Apps(62)-通信:Socket TCP、Socket UDPを再想像
作者:webabcd紹介Windows 8 Store Appsの再想像 通信
<Page
x:Class="XamlDemo.Communication.Socket.TcpDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
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">
<StackPanel Margin="120 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 10 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 10 0 0" />
</StackPanel>
<TextBlock Name="lblMsg" FontSize="14.667" TextWrapping="Wrap" Margin="20 0 0 0" />
</StackPanel>
</Grid>
</Page>
Communication/Socket/TcpDemo.xaml.cs/*
* socket tcp ( )
*
* StreamSocketListener tcp socket
* StreamSocket tcp socket
*
* : Package.appxmanifest <Capability Name="privateNetworkClientServer" />
*/
using 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>
/// socket
/// </summary>
private StreamSocketListener _listener;
/// <summary>
/// socket
/// </summary>
private StreamSocket _client;
/// <summary>
/// DataWriter
/// </summary>
private DataWriter _writer;
public TcpDemo()
{
this.InitializeComponent();
}
// socket
private async void btnStartListener_Click(object sender, RoutedEventArgs e)
{
// socket
_listener = new StreamSocketListener();
//
_listener.ConnectionReceived += _listener_ConnectionReceived;
try
{
// socket
await _listener.BindServiceNameAsync("2211");
lblMsg.Text += " 2211 socket(tcp) ";
lblMsg.Text += Environment.NewLine;
}
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
async void _listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
// DataReader,
DataReader reader = new DataReader(args.Socket.InputStream);
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
lblMsg.Text += " : " + args.Socket.Information.RemoteHostName.RawName + ":" + args.Socket.Information.RemotePort + " socket ";
lblMsg.Text += Environment.NewLine;
});
try
{
while (true)
{
// (header|body): 4 ,
// header
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
// ,socket
return;
}
// body
uint stringLength = reader.ReadUInt32();
uint actualStringLength = await reader.LoadAsync(stringLength);
if (stringLength != actualStringLength)
{
// ,socket
return;
}
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
//
lblMsg.Text += " : " + reader.ReadString(actualStringLength);
lblMsg.Text += Environment.NewLine;
});
}
}
catch (Exception ex)
{
var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
SocketErrorStatus errStatus = SocketError.GetStatus(ex.HResult);
lblMsg.Text += "errStatus: " + errStatus.ToString();
lblMsg.Text += Environment.NewLine;
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewLine;
});
}
}
// socket, socket
private async void btnConnectListener_Click(object sender, RoutedEventArgs e)
{
HostName hostName;
try
{
hostName = new HostName("127.0.0.1");
}
catch (Exception ex)
{
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewLine;
return;
}
// socket
_client = new StreamSocket();
try
{
// socket
await _client.ConnectAsync(hostName, "2211");
lblMsg.Text += " 127.0.0.1:2211";
lblMsg.Text += Environment.NewLine;
}
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 socket
private async void btnSendData_Click(object sender, RoutedEventArgs e)
{
// DataWriter,
if (_writer == null)
_writer = new DataWriter(_client.OutputStream);
// (header|body): 4 ,
string data = "hello webabcd " + DateTime.Now.ToString("hh:mm:ss");
_writer.WriteUInt32(_writer.MeasureString(data)); // header
_writer.WriteString(data); // body
try
{
//
await _writer.StoreAsync();
lblMsg.Text += " : " + data;
lblMsg.Text += Environment.NewLine;
}
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 socket
private void btnCloseSocket_Click(object sender, RoutedEventArgs e)
{
try
{
_writer.DetachStream(); // DataWriter Stream
_writer.Dispose();
_client.Dispose();
_listener.Dispose();
lblMsg.Text += " socket socket ";
lblMsg.Text += Environment.NewLine;
}
catch (Exception ex)
{
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewLine;
}
}
}
}
2、プレゼンテーションsocketのアプリケーション(どのようにhttp serverを実現しますか?このhttp serverはこのapp内部でしか呼び出しできません。外部では呼び出しできません。)Communication/Socket/CustoomatHttp Server.xaml<Page
x:Class="XamlDemo.Communication.Socket.CustomHttpServer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
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">
<StackPanel Margin="120 0 0 0" Orientation="Horizontal">
<StackPanel>
<Button Name="btnLaunchHttpServer" Content=" http server" Click="btnLaunchHttpServer_Click" />
<Button Name="btnRequestHttpServer" Content=" http server" Click="btnRequestHttpServer_Click" Margin="0 10 0 0" />
<Button Name="btnCloseHttpServer" Content=" http server" Click="btnCloseHttpServer_Click" Margin="0 10 0 0" />
</StackPanel>
<TextBlock Name="lblMsg" FontSize="14.667" TextWrapping="Wrap" Margin="20 0 0 0" />
</StackPanel>
</Grid>
</Page>
Communication/Socket/CustoomHttp Server.xaml.cs/*
* socket ( http server, http server app , )
*
* : Package.appxmanifest <Capability Name="privateNetworkClientServer" />
*/
using System;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Text;
using System.Net.Http;
namespace XamlDemo.Communication.Socket
{
public sealed partial class CustomHttpServer : Page
{
/// <summary>
/// http server socket
/// </summary>
private StreamSocketListener _listener;
public CustomHttpServer()
{
this.InitializeComponent();
}
// http server, socket
private async void btnLaunchHttpServer_Click(object sender, RoutedEventArgs e)
{
// socket
_listener = new StreamSocketListener();
//
_listener.ConnectionReceived += _listener_ConnectionReceived;
try
{
// socket
await _listener.BindServiceNameAsync("2212");
lblMsg.Text += " 2212 socket , http server :http://localhost:2212/";
lblMsg.Text += Environment.NewLine;
}
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 , http
async void _listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
// DataReader,
DataReader reader = new DataReader(args.Socket.InputStream);
try
{
// http header
StringBuilder sb = new StringBuilder();
while (true)
{
//
uint loaded = await reader.LoadAsync(1);
if (loaded != 1)
return;
char c = (char)reader.ReadByte();
sb.Append(c);
// \r
\r
header
if (sb.ToString().IndexOf("\r
\r
") > 0)
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
lblMsg.Text += " http request header: ";
lblMsg.Text += Environment.NewLine;
lblMsg.Text += sb.ToString();
lblMsg.Text += Environment.NewLine;
});
// http
string response = "";
// http
response += "HTTP/1.1 200 OK";
response += "Content-Type:text/html\r
";
response += "Server:Custom Http Server\r
";
response += "Content-Length:2\r
";
response += "Connection: Keep-Alive\r
\r
"; // \r
\r
//
response += "ok";
//
DataWriter writer = new DataWriter(args.Socket.OutputStream);
writer.WriteString(response);
await writer.StoreAsync();
sb.Clear();
}
}
}
catch (Exception ex)
{
var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
SocketErrorStatus errStatus = SocketError.GetStatus(ex.HResult);
lblMsg.Text += "errStatus: " + errStatus.ToString();
lblMsg.Text += Environment.NewLine;
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewLine;
});
}
}
private async void btnRequestHttpServer_Click(object sender, RoutedEventArgs e)
{
HttpClient client = new HttpClient();
// http server
string result = await client.GetStringAsync(new Uri("http://localhost:2212/abc.html"));
// http server
lblMsg.Text += "response: " + result;
lblMsg.Text += Environment.NewLine;
}
// http server, socket
private void btnCloseHttpServer_Click(object sender, RoutedEventArgs e)
{
try
{
_listener.Dispose();
lblMsg.Text += "http server ";
lblMsg.Text += Environment.NewLine;
}
catch (Exception ex)
{
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewLine;
}
}
}
}
3、socket upのアプリケーションをデモンストレーションする(この例はサービスをしながらクライアントをする)Communication/Socket/UdpDemo.xaml<Page
x:Class="XamlDemo.Communication.Socket.UdpDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
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">
<StackPanel Margin="120 0 0 0" Orientation="Horizontal">
<StackPanel>
<Button Name="btnStartListener" Content="start a socket listener" Click="btnStartListener_Click" />
<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 10 0 0" />
</StackPanel>
<TextBlock Name="lblMsg" FontSize="14.667" TextWrapping="Wrap" Margin="20 0 0 0" />
</StackPanel>
</Grid>
</Page>
Communication/Socket/UdpDemo.xaml.cs/*
* socket udp ( )
*
* DatagramSocket udp
*
* : Package.appxmanifest <Capability Name="privateNetworkClientServer" />
* :udp (Datagram) 65535( )
*/
using System;
using System.Threading;
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 UdpDemo : Page
{
/// <summary>
/// socket
/// </summary>
private DatagramSocket _listener;
/// <summary>
/// socket
/// </summary>
private DatagramSocket _client;
/// <summary>
/// DataWriter
/// </summary>
private DataWriter _writer;
public UdpDemo()
{
this.InitializeComponent();
}
// socket
private async void btnStartListener_Click(object sender, RoutedEventArgs e)
{
// socket
_listener = new DatagramSocket();
//
_listener.MessageReceived += _listener_MessageReceived;
try
{
// socket
await _listener.BindServiceNameAsync("2213");
lblMsg.Text += " 2213 socket(udp) ";
lblMsg.Text += Environment.NewLine;
}
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 udp
private void _listener_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
try
{
//
DataReader dataReader = args.GetDataReader();
uint stringLength = dataReader.UnconsumedBufferLength;
var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
lblMsg.Text += " : " + dataReader.ReadString(stringLength) + " - : " + args.RemoteAddress.RawName + ":" + args.RemotePort;
lblMsg.Text += Environment.NewLine;
});
}
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 socket
private async void btnSendData_Click(object sender, RoutedEventArgs e)
{
if (_client == null)
{
HostName hostName;
try
{
hostName = new HostName("127.0.0.1");
}
catch (Exception ex)
{
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewLine;
return;
}
try
{
// DatagramSocket, 127.0.0.1:2213
_client = new DatagramSocket();
await _client.ConnectAsync(hostName, "2213"); // ConnectAsync() ,udp ,
lblMsg.Text += " 127.0.0.1:2213 ";
lblMsg.Text += Environment.NewLine;
}
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;
}
}
// DataWriter,
if (_writer == null)
_writer = new DataWriter(_client.OutputStream);
try
{
string data = "hello webabcd " + DateTime.Now.ToString("hh:mm:ss");
_writer.WriteString(data);
//
await _writer.StoreAsync();
lblMsg.Text += " : " + data;
lblMsg.Text += Environment.NewLine;
}
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 socket
private void btnCloseSocket_Click(object sender, RoutedEventArgs e)
{
try
{
_writer.DetachStream(); // DataWriter Stream
_writer.Dispose();
_client.Dispose();
_listener.Dispose();
lblMsg.Text += " socket socket ";
lblMsg.Text += Environment.NewLine;
}
catch (Exception ex)
{
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewLine;
}
}
}
}
OK [ソースのダウンロード]