Socket 常用类型
StreamSocket:Socket对象
StreamSocketListener:Socket监听对象,适用于服务端
服务端代码
<Grid x:Name="LayoutRoot"> <Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions> <!-- 标题面板 -->
<StackPanel Grid.Row="0" Margin="19,0,0,0">
<TextBlock Text="Socket Chat" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
<TextBlock Text="Server" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
</StackPanel> <!--TODO: 应将内容放入以下网格-->
<Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0"> <Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions> <ListView x:Name="messageList" Grid.Row="0"/> <Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions> <TextBox x:Name="txtMessage" Grid.Column="0"/>
<Button
x:Name="btnSend"
Grid.Column="1"
Content="Send"
Click="btnSend_Click"/> </Grid>
</Grid> </Grid> <!--<Page.BottomAppBar>
<CommandBar>
<AppBarButton Icon="Send" Label="Send"/>
</CommandBar>
</Page.BottomAppBar>-->
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
// 建立服务端监听
StreamSocketListener listener = new StreamSocketListener();
listener.ConnectionReceived += listener_ConnectionReceived;
try
{
await listener.BindServiceNameAsync("");
System.Diagnostics.Debug.WriteLine("服务端启动监听。。。");
}
catch (Exception ex)
{
var status = SocketError.GetStatus(ex.HResult);
System.Diagnostics.Debug.WriteLine("服务端监听失败。。。");
// 退出应用程序(NotRunning)
App.Current.Exit();
}
}
private List<StreamSocket> clients = new List<StreamSocket>();
async void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
var clientSocket = args.Socket;
clients.Add(clientSocket);
// 有一个Socket客户端连接上了
System.Diagnostics.Debug.WriteLine("有人来了。。。" + clientSocket.Information.RemoteAddress); DataReader reader = new DataReader(clientSocket.InputStream);
while (true)
{
// 不断接收客户端传过来的数据 #region 读取数据中数据头(数据的大小) var length = await reader.LoadAsync(sizeof(uint));
if (length != sizeof(uint))
{
// 客户端发送过来的数据不合法
// 客户端断开连接
System.Diagnostics.Debug.WriteLine(string.Format("客户端{0}断开连接", clientSocket.Information.RemoteAddress));
break;
}
// 客户端发送过来的数据是合法数据
// 读取真实数据长度
var messageLength = reader.ReadUInt32(); #endregion #region 根据数据大小创建缓冲区读取真实数据内容
// 根据真实长度创建内容数据缓冲
var messageLength2 = await reader.LoadAsync(messageLength); if (messageLength2 != messageLength)
{
// 客户端发送过来的数据不合法
// 客户端断开连接
System.Diagnostics.Debug.WriteLine(string.Format("客户端{0}断开连接", clientSocket.Information.RemoteAddress));
break;
} var message = reader.ReadString(messageLength2); #endregion
// 客户端发送过来的数据是合法数据
//var length = reader.ReadUInt32(); // 不再是UI线程执行以下代码
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
// 该方法会被主线程执行
messageList.Items.Add(string.Format("{1}说:{0}", message, clientSocket.Information.RemoteAddress));
});
//var result = await reader.LoadAsync();
}
} private async void btnSend_Click(object sender, RoutedEventArgs e)
{
foreach (var item in clients)
{
// 发送数据消息
// 先拿到当前建立完连接的Socket
var message = txtMessage.Text; DataWriter writer = new DataWriter(item.OutputStream);
// 先往发送流中写入数据大小
writer.WriteUInt32(writer.MeasureString(message));
// 再将数据写入发送流
writer.WriteString(message);
// 将数据提交到服务端
await writer.StoreAsync();
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
messageList.Items.Add(string.Format("我说:{0}", message));
});
}
}
客户端代码
<Grid x:Name="LayoutRoot"> <Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions> <!-- 标题面板 -->
<StackPanel Grid.Row="0" Margin="19,0,0,0">
<TextBlock Text="Socket Chat" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
<TextBlock Text="Client" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
</StackPanel> <!--TODO: 应将内容放入以下网格-->
<Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0"> <Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions> <ListView x:Name="messageList" Grid.Row="0"/> <Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions> <TextBox x:Name="txtMessage" Grid.Column="0"/>
<Button
x:Name="btnSend"
Grid.Column="1"
Content="Send"
Click="btnSend_Click"/> </Grid>
</Grid> </Grid>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
string ip = "127.0.0.1";
int port = ;
HostName host = new HostName(ip);
// 建立Socket连接
socket = new StreamSocket();
try
{
await socket.ConnectAsync(host, port.ToString()); DataReader reader = new DataReader(socket.InputStream); while (true)
{
// 不断接收客户端传过来的数据 #region 读取数据中数据头(数据的大小) var length = await reader.LoadAsync(sizeof(uint));
if (length != sizeof(uint))
{
// 客户端发送过来的数据不合法
// 客户端断开连接
System.Diagnostics.Debug.WriteLine(string.Format("客户端{0}断开连接", socket.Information.RemoteAddress));
break;
}
// 客户端发送过来的数据是合法数据
// 读取真实数据长度
var messageLength = reader.ReadUInt32(); #endregion #region 根据数据大小创建缓冲区读取真实数据内容
// 根据真实长度创建内容数据缓冲
var messageLength2 = await reader.LoadAsync(messageLength); if (messageLength2 != messageLength)
{
// 客户端发送过来的数据不合法
// 客户端断开连接
System.Diagnostics.Debug.WriteLine(string.Format("客户端{0}断开连接", socket.Information.RemoteAddress));
break;
} var message = reader.ReadString(messageLength2); #endregion
// 客户端发送过来的数据是合法数据
//var length = reader.ReadUInt32(); // 不再是UI线程执行以下代码
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
// 该方法会被主线程执行
messageList.Items.Add(string.Format("{1}说:{0}", message, socket.Information.RemoteAddress));
});
//var result = await reader.LoadAsync();
}
}
catch (Exception ex)
{
//
var status = SocketError.GetStatus(ex.HResult);
System.Diagnostics.Debug.WriteLine("建立连接失败" + status);
App.Current.Exit();
}
} private async void btnSend_Click(object sender, RoutedEventArgs e)
{
// 发送数据消息
// 先拿到当前建立完连接的Socket
var message = txtMessage.Text; DataWriter writer = new DataWriter(socket.OutputStream);
// 先往发送流中写入数据大小
writer.WriteUInt32(writer.MeasureString(message));
// 再将数据写入发送流
writer.WriteString(message);
// 将数据提交到服务端
await writer.StoreAsync();
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
messageList.Items.Add(string.Format("我说:{0}", message));
});
}