Socket 常用类型
StreamSocket:Socket对象
StreamSocketListener:Socket监听对象,适用于服务端
服务端代码
1 <Grid x:Name="LayoutRoot"> 2 3 <Grid.RowDefinitions> 4 <RowDefinition Height="Auto"/> 5 <RowDefinition Height="*"/> 6 </Grid.RowDefinitions> 7 8 <!-- 标题面板 --> 9 <StackPanel Grid.Row="0" Margin="19,0,0,0"> 10 <TextBlock Text="Socket Chat" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/> 11 <TextBlock Text="Server" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/> 12 </StackPanel> 13 14 <!--TODO: 应将内容放入以下网格--> 15 <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0"> 16 17 <Grid.RowDefinitions> 18 <RowDefinition/> 19 <RowDefinition Height="auto"/> 20 </Grid.RowDefinitions> 21 22 <ListView x:Name="messageList" Grid.Row="0"/> 23 24 <Grid Grid.Row="1"> 25 <Grid.ColumnDefinitions> 26 <ColumnDefinition/> 27 <ColumnDefinition Width="auto"/> 28 </Grid.ColumnDefinitions> 29 30 <TextBox x:Name="txtMessage" Grid.Column="0"/> 31 <Button 32 x:Name="btnSend" 33 Grid.Column="1" 34 Content="Send" 35 Click="btnSend_Click"/> 36 37 </Grid> 38 </Grid> 39 40 </Grid> 41 42 <!--<Page.BottomAppBar> 43 <CommandBar> 44 <AppBarButton Icon="Send" Label="Send"/> 45 </CommandBar> 46 </Page.BottomAppBar>-->
1 protected async override void OnNavigatedTo(NavigationEventArgs e) 2 { 3 // 建立服务端监听 4 StreamSocketListener listener = new StreamSocketListener(); 5 listener.ConnectionReceived += listener_ConnectionReceived; 6 try 7 { 8 await listener.BindServiceNameAsync("10086"); 9 System.Diagnostics.Debug.WriteLine("服务端启动监听。。。"); 10 } 11 catch (Exception ex) 12 { 13 var status = SocketError.GetStatus(ex.HResult); 14 System.Diagnostics.Debug.WriteLine("服务端监听失败。。。"); 15 // 退出应用程序(NotRunning) 16 App.Current.Exit(); 17 } 18 } 19 private List<StreamSocket> clients = new List<StreamSocket>(); 20 async void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) 21 { 22 var clientSocket = args.Socket; 23 clients.Add(clientSocket); 24 // 有一个Socket客户端连接上了 25 System.Diagnostics.Debug.WriteLine("有人来了。。。" + clientSocket.Information.RemoteAddress); 26 27 DataReader reader = new DataReader(clientSocket.InputStream); 28 while (true) 29 { 30 // 不断接收客户端传过来的数据 31 32 #region 读取数据中数据头(数据的大小) 33 34 var length = await reader.LoadAsync(sizeof(uint)); 35 if (length != sizeof(uint)) 36 { 37 // 客户端发送过来的数据不合法 38 // 客户端断开连接 39 System.Diagnostics.Debug.WriteLine(string.Format("客户端{0}断开连接", clientSocket.Information.RemoteAddress)); 40 break; 41 } 42 // 客户端发送过来的数据是合法数据 43 // 读取真实数据长度 44 var messageLength = reader.ReadUInt32(); 45 46 #endregion 47 48 #region 根据数据大小创建缓冲区读取真实数据内容 49 // 根据真实长度创建内容数据缓冲 50 var messageLength2 = await reader.LoadAsync(messageLength); 51 52 if (messageLength2 != messageLength) 53 { 54 // 客户端发送过来的数据不合法 55 // 客户端断开连接 56 System.Diagnostics.Debug.WriteLine(string.Format("客户端{0}断开连接", clientSocket.Information.RemoteAddress)); 57 break; 58 } 59 60 var message = reader.ReadString(messageLength2); 61 62 #endregion 63 // 客户端发送过来的数据是合法数据 64 //var length = reader.ReadUInt32(); 65 66 // 不再是UI线程执行以下代码 67 await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => 68 { 69 // 该方法会被主线程执行 70 messageList.Items.Add(string.Format("{1}说:{0}", message, clientSocket.Information.RemoteAddress)); 71 }); 72 //var result = await reader.LoadAsync(); 73 } 74 } 75 76 private async void btnSend_Click(object sender, RoutedEventArgs e) 77 { 78 foreach (var item in clients) 79 { 80 // 发送数据消息 81 // 先拿到当前建立完连接的Socket 82 var message = txtMessage.Text; 83 84 DataWriter writer = new DataWriter(item.OutputStream); 85 // 先往发送流中写入数据大小 86 writer.WriteUInt32(writer.MeasureString(message)); 87 // 再将数据写入发送流 88 writer.WriteString(message); 89 // 将数据提交到服务端 90 await writer.StoreAsync(); 91 await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => 92 { 93 messageList.Items.Add(string.Format("我说:{0}", message)); 94 }); 95 } 96 }
客户端代码
1 <Grid x:Name="LayoutRoot"> 2 3 <Grid.RowDefinitions> 4 <RowDefinition Height="Auto"/> 5 <RowDefinition Height="*"/> 6 </Grid.RowDefinitions> 7 8 <!-- 标题面板 --> 9 <StackPanel Grid.Row="0" Margin="19,0,0,0"> 10 <TextBlock Text="Socket Chat" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/> 11 <TextBlock Text="Client" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/> 12 </StackPanel> 13 14 <!--TODO: 应将内容放入以下网格--> 15 <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0"> 16 17 <Grid.RowDefinitions> 18 <RowDefinition/> 19 <RowDefinition Height="auto"/> 20 </Grid.RowDefinitions> 21 22 <ListView x:Name="messageList" Grid.Row="0"/> 23 24 <Grid Grid.Row="1"> 25 <Grid.ColumnDefinitions> 26 <ColumnDefinition/> 27 <ColumnDefinition Width="auto"/> 28 </Grid.ColumnDefinitions> 29 30 <TextBox x:Name="txtMessage" Grid.Column="0"/> 31 <Button 32 x:Name="btnSend" 33 Grid.Column="1" 34 Content="Send" 35 Click="btnSend_Click"/> 36 37 </Grid> 38 </Grid> 39 40 </Grid>
1 protected async override void OnNavigatedTo(NavigationEventArgs e) 2 { 3 string ip = "127.0.0.1"; 4 int port = 10086; 5 HostName host = new HostName(ip); 6 // 建立Socket连接 7 socket = new StreamSocket(); 8 try 9 { 10 await socket.ConnectAsync(host, port.ToString()); 11 12 DataReader reader = new DataReader(socket.InputStream); 13 14 while (true) 15 { 16 // 不断接收客户端传过来的数据 17 18 #region 读取数据中数据头(数据的大小) 19 20 var length = await reader.LoadAsync(sizeof(uint)); 21 if (length != sizeof(uint)) 22 { 23 // 客户端发送过来的数据不合法 24 // 客户端断开连接 25 System.Diagnostics.Debug.WriteLine(string.Format("客户端{0}断开连接", socket.Information.RemoteAddress)); 26 break; 27 } 28 // 客户端发送过来的数据是合法数据 29 // 读取真实数据长度 30 var messageLength = reader.ReadUInt32(); 31 32 #endregion 33 34 #region 根据数据大小创建缓冲区读取真实数据内容 35 // 根据真实长度创建内容数据缓冲 36 var messageLength2 = await reader.LoadAsync(messageLength); 37 38 if (messageLength2 != messageLength) 39 { 40 // 客户端发送过来的数据不合法 41 // 客户端断开连接 42 System.Diagnostics.Debug.WriteLine(string.Format("客户端{0}断开连接", socket.Information.RemoteAddress)); 43 break; 44 } 45 46 var message = reader.ReadString(messageLength2); 47 48 #endregion 49 // 客户端发送过来的数据是合法数据 50 //var length = reader.ReadUInt32(); 51 52 // 不再是UI线程执行以下代码 53 await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => 54 { 55 // 该方法会被主线程执行 56 messageList.Items.Add(string.Format("{1}说:{0}", message, socket.Information.RemoteAddress)); 57 }); 58 //var result = await reader.LoadAsync(); 59 } 60 } 61 catch (Exception ex) 62 { 63 // 1102202 64 var status = SocketError.GetStatus(ex.HResult); 65 System.Diagnostics.Debug.WriteLine("建立连接失败" + status); 66 App.Current.Exit(); 67 } 68 } 69 70 private async void btnSend_Click(object sender, RoutedEventArgs e) 71 { 72 // 发送数据消息 73 // 先拿到当前建立完连接的Socket 74 var message = txtMessage.Text; 75 76 DataWriter writer = new DataWriter(socket.OutputStream); 77 // 先往发送流中写入数据大小 78 writer.WriteUInt32(writer.MeasureString(message)); 79 // 再将数据写入发送流 80 writer.WriteString(message); 81 // 将数据提交到服务端 82 await writer.StoreAsync(); 83 await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => 84 { 85 messageList.Items.Add(string.Format("我说:{0}", message)); 86 }); 87 }