Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

Hope Studio's official website

希望工作室的官方网站

嗨嗨嗨我又来了!

这几天我在编写WinUI3和UWP。因为我的小米4搭载了先进的Windows Phone10。接下来,我将展示一个多线程聊天室的代码并分享软件包(.7z)。
我是参考了一位CSDN大牛的文章:https://blog.csdn.net/weixin_42582160/article/details/122262483
并且使用了一点科技的力量(DeepSeek)做的。
截图

以下是主要代码:

xaml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<Page
x:Class="SimpleChat.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SimpleChat"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>

<!-- 聊天显示区域 -->
<ScrollViewer Grid.Column="0" Grid.Row="0" VerticalScrollBarVisibility="Auto">
<TextBox x:Name="ChatEdit" IsReadOnly="True" AcceptsReturn="True" TextWrapping="Wrap"/>
</ScrollViewer>

<!-- 输入框 -->
<TextBox x:Name="InputLine" Grid.Column="0" Grid.Row="1" PlaceholderText="在此输入消息..."/>

<!-- 发送按钮 -->
<Button x:Name="SendBtn" Grid.Column="1" Grid.Row="1" Content="发送" Click="SendBtn_Click"/>

<!-- 配置面板 -->
<StackPanel Grid.Column="1" Grid.Row="0" Margin="10">
<TextBlock Text="服务器 IP"/>
<TextBox x:Name="IpEdit" PlaceholderText="输入 IP 地址"/>
<Button x:Name="HostIpBtn" Content="获取本机 IP" Click="HostIpBtn_Click"/>
<TextBlock Text="服务器端口"/>
<TextBox x:Name="PortEdit" PlaceholderText="输入端口"/>
<TextBlock Text="昵称"/>
<TextBox x:Name="HostEdit" PlaceholderText="输入昵称"/>
<RadioButton x:Name="ServerRbtn" Content="服务器" Checked="ServerRbtn_Checked"/>
<RadioButton x:Name="ClientRbtn" Content="客户端" Checked="ClientRbtn_Checked"/>
<Button x:Name="ConnectBtn" Content="连接服务器" Click="ConnectBtn_Click"/>
<Button x:Name="BuildServerBtn" Content="创建服务器" Click="BuildServerBtn_Click"/>
<Button x:Name="QuitBtn" Content="退出" Click="QuitBtn_Click"/>

</StackPanel>
</Grid>
</Page>

csharp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.ViewManagement;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;

namespace SimpleChat
{
public sealed partial class MainPage : Page
{
private StreamSocket _socket; // 服务器或客户端 StreamSocket
private bool _isServer = true; // 是否为服务器模式
private bool _isRunning = false; // 服务器是否正在运行
private List &lt;StreamSocket> _clientSockets = new List &lt;StreamSocket>(); // 客户端列表

public MainPage()
{
this.InitializeComponent();

// 设置窗口标题
var view = ApplicationView.GetForCurrentView();
view.Title = "SimpleChat";
}

// 发送消息按钮点击事件
private void SendBtn_Click(object sender, RoutedEventArgs e)
{
string message = InputLine.Text;
if (!string.IsNullOrEmpty(message))
{
string hostName = HostEdit.Text.Trim();
if (string.IsNullOrEmpty(hostName))
{
hostName = "Anonymous"; // 默认昵称
}

string fullMessage = $"{hostName}: {message}";
InputLine.Text = string.Empty; // 清空输入框

if (_isServer)
{
// 如果是服务器,在本地显示 "You: sth"
ChatEdit.Text += $"{Environment.NewLine}You: {message}";

// 广播消息给所有客户端(不包括自己)
BroadcastMessage(fullMessage);
}
else
{
// 如果是客户端,在本地显示 "You: sth"
ChatEdit.Text += $"{Environment.NewLine}You: {message}";

// 发送消息到服务器
SendMessageToServer(fullMessage);
}
}
}

// 获取本机 IP 按钮点击事件
private void HostIpBtn_Click(object sender, RoutedEventArgs e)
{
var hostNames = Windows.Networking.Connectivity.NetworkInformation.GetHostNames();
foreach (var hostName in hostNames)
{
if (hostName.Type == Windows.Networking.HostNameType.Ipv4)
{
IpEdit.Text = hostName.ToString();
break;
}
}
}

// 服务器模式单选按钮点击事件
private void ServerRbtn_Checked(object sender, RoutedEventArgs e)
{
_isServer = true;
ConnectBtn.IsEnabled = false;
BuildServerBtn.IsEnabled = true;
}

// 客户端模式单选按钮点击事件
private void ClientRbtn_Checked(object sender, RoutedEventArgs e)
{
_isServer = false;
ConnectBtn.IsEnabled = true;
BuildServerBtn.IsEnabled = false;
}

// 连接服务器按钮点击事件
private async void ConnectBtn_Click(object sender, RoutedEventArgs e)
{
if (!_isServer)
{
string ip = IpEdit.Text.Trim();
if (string.IsNullOrEmpty(ip))
{
ChatEdit.Text += $"{Environment.NewLine}IP address cannot be empty!";
return;
}

if (!int.TryParse(PortEdit.Text, out int port))
{
ChatEdit.Text += $"{Environment.NewLine}Invalid port number!";
return;
}

await ConnectToServerAsync(ip, port);
}
}

// 创建服务器按钮点击事件
private async void BuildServerBtn_Click(object sender, RoutedEventArgs e)
{
if (_isServer)
{
string ip = IpEdit.Text.Trim();
if (string.IsNullOrEmpty(ip))
{
ChatEdit.Text += $"{Environment.NewLine}IP address cannot be empty!";
return;
}

if (!int.TryParse(PortEdit.Text, out int port))
{
ChatEdit.Text += $"{Environment.NewLine}Invalid port number!";
return;
}

await StartServerAsync(ip, port);
}
}

// 退出按钮点击事件
private void QuitBtn_Click(object sender, RoutedEventArgs e)
{
if (_socket != null)
{
_socket.Dispose();
}
Application.Current.Exit();
}

// 启动服务器
private async Task StartServerAsync(string ip, int port)
{
try
{
var listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnectionReceived;
await listener.BindEndpointAsync(new HostName(ip), port.ToString());

_isRunning = true;
string hostName = HostEdit.Text.Trim();
if (string.IsNullOrEmpty(hostName))
{
hostName = "Server"; // 默认服务器名称
}
ChatEdit.Text += $"{Environment.NewLine}{hostName} started on {ip}:{port}";
}
catch (Exception ex)
{
ChatEdit.Text += $"{Environment.NewLine}Server error: {ex.Message}";
}
}

private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
var clientSocket = args.Socket;
_clientSockets.Add(clientSocket);

await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ChatEdit.Text += $"{Environment.NewLine}Client connected: {clientSocket.Information.RemoteAddress}";
});

_ = Task.Run(() => HandleClientAsync(clientSocket));
}

// 处理客户端连接
private async Task HandleClientAsync(StreamSocket clientSocket)
{
try
{
var reader = new DataReader(clientSocket.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;

while (true)
{
await reader.LoadAsync(1024);
if (reader.UnconsumedBufferLength == 0) break; // 客户端断开连接

string message = reader.ReadString(reader.UnconsumedBufferLength);
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ChatEdit.Text += $"{Environment.NewLine}{message}"; // 服务器显示消息
});

// 广播消息给所有客户端(不包括发送者)
BroadcastMessage(message, clientSocket);
}
}
catch (Exception ex)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ChatEdit.Text += $"{Environment.NewLine}Client error: {ex.Message}";
});
}
finally
{
_clientSockets.Remove(clientSocket);
clientSocket.Dispose();
}
}

// 广播消息给所有客户端(不包括发送者)
private async void BroadcastMessage(string message, StreamSocket senderSocket = null)
{
foreach (var clientSocket in _clientSockets)
{
if (clientSocket != senderSocket)
{
var writer = new DataWriter(clientSocket.OutputStream);
writer.WriteString(message);
await writer.StoreAsync();
writer.DetachStream();
}
}
}

// 连接到服务器
private async Task ConnectToServerAsync(string ip, int port)
{
try
{
_socket = new StreamSocket();
await _socket.ConnectAsync(new HostName(ip), port.ToString());

ChatEdit.Text += $"{Environment.NewLine}Connected to server at {ip}:{port}";

// 启动接收消息的任务
_ = Task.Run(() => ReceiveMessagesAsync(_socket));
}
catch (Exception ex)
{
ChatEdit.Text += $"{Environment.NewLine}Connection error: {ex.Message}";
}
}

// 接收服务器消息
private async Task ReceiveMessagesAsync(StreamSocket socket)
{
try
{
var reader = new DataReader(socket.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;

while (true)
{
await reader.LoadAsync(1024);
if (reader.UnconsumedBufferLength == 0) break; // 服务器断开连接

string message = reader.ReadString(reader.UnconsumedBufferLength);
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ChatEdit.Text += $"{Environment.NewLine}{message}"; // 客户端显示消息
});
}
}
catch (Exception ex)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ChatEdit.Text += $"{Environment.NewLine}Receive error: {ex.Message}";
});
}
}

// 发送消息到服务器
private async void SendMessageToServer(string message)
{
if (_socket != null)
{
var writer = new DataWriter(_socket.OutputStream);
writer.WriteString(message);
await writer.StoreAsync();
writer.DetachStream();
}
}
}
}

666这个代码框眼都不演了。

这里是我打包过的(Appxbundle不含arm64)版本是1.0.3.0

https://www.123865.com/s/qPh5Vv-kajN
https://www.123684.com/s/qPh5Vv-kajN
好了就到这里吧。

评论