1.Xaml
<Window x:Class="Server.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Server"
mc:Ignorable="d"
xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
WindowStartupLocation="CenterScreen" ResizeMode="NoResize"
Loaded="MainWindow_OnLoaded"
Title="Server" Height="450" Width="600">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<TreeView x:Name="tvRemotes">
</TreeView>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Right" Margin="5,0,2,0" Padding="5" Text="本地地址"/>
<TextBox x:Name="tbIP" IsReadOnly="True" Grid.Row="0" Grid.Column="1" Margin="5" Text="127.0.0.1" />
<TextBlock HorizontalAlignment="Right" Margin="5,0,2,0" Padding="5" Grid.Row="1" Grid.Column="0" Text="本地端口:"/>
<TextBox x:Name="tbPort" Grid.Row="1" Grid.Column="1" Margin="5"/>
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal">
<Button x:Name="btnListen" Content="开始监听" Margin="15" Click="BtnListen_OnClick"/>
<Button x:Name="btnDisconnect" Content="断开连接" IsEnabled="False" Margin="15" Click="BtnDisconnect_OnClick"/>
</StackPanel>
<ListView x:Name="lvDebugs" Grid.Row="3" Grid.ColumnSpan="2" Grid.Column="0" AlternationCount="2">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="ListView.AlternationIndex" Value="0">
<Setter Property="Background" Value="White"/>
</Trigger>
<Trigger Property="ListView.AlternationIndex" Value="1">
<Setter Property="Background" Value="WhiteSmoke"/>
</Trigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
</ListView>
</Grid>
</Grid>
</Window>
2.CSharp
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading; namespace Server
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private TcpListener listener = null;
private List<Socket> socketList = new List<Socket>(); public class StateObject
{
public Socket workSocket = null;
public const int BUFFER_SIZE = ;
public byte[] buffer = new byte[BUFFER_SIZE];
} public MainWindow()
{
InitializeComponent();
} private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{ } /// <summary>
/// 开启监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnListen_OnClick(object sender, RoutedEventArgs e)
{
try
{
listener = new TcpListener(new IPEndPoint(IPAddress.Any, Convert.ToInt32(tbPort.Text)));
listener.Start();
listener.BeginAcceptSocket(new AsyncCallback(AcceptCallback), listener.Server); btnListen.IsEnabled = false;
btnDisconnect.IsEnabled = true;
}
catch (Exception ex)
{
Add2ListView("启动监听异常: " + ex.Message);
}
} private void AcceptCallback(IAsyncResult ar)
{
Socket server = (Socket) ar.AsyncState;
try
{
Socket socket = server.EndAccept(ar);
string strAddr = socket.RemoteEndPoint.ToString();
socketList.Add(socket);
Dispatcher.Invoke(() =>
{
Add2TreeView(strAddr);
Add2ListView(strAddr);
}, DispatcherPriority.Normal);
var bytes = Encoding.UTF8.GetBytes("welcome.");
socket.Send(bytes);
StateObject so = new StateObject();
so.workSocket = socket;
socket.BeginReceive(so.buffer, , StateObject.BUFFER_SIZE, SocketFlags.None,
new AsyncCallback(ReceiveCallback), so); server.BeginAccept(new AsyncCallback(AcceptCallback), server);
}
catch (Exception)
{
// ignored
}
} /// <summary>
/// 断开监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void BtnDisconnect_OnClick(object sender, RoutedEventArgs e)
{
try
{
foreach (var socket in socketList)
{
if (socket != null && socket.Connected)
{
socket.Shutdown(SocketShutdown.Both); await Task.Delay();
socket.Close();
}
}
socketList.Clear(); listener.Stop();
// 清空客户端列表
tvRemotes.Items.Clear(); btnListen.IsEnabled = true;
btnDisconnect.IsEnabled = false;
}
catch (Exception ex)
{
Add2ListView("断开监听异常: " + ex.Message);
}
} private void ReceiveCallback(IAsyncResult ar)
{
StateObject so = ar.AsyncState as StateObject;
Socket socket = so.workSocket;
if (socket != null && socket.Connected)
{
int read = socket.EndReceive(ar);
ar.AsyncWaitHandle.Close();
if (read > )
{
Dispatcher.Invoke(() => Add2ListView(text: socket.RemoteEndPoint + ": " + Encoding.UTF8.GetString(so.buffer)),
DispatcherPriority.Normal);
socket.BeginReceive(so.buffer, , StateObject.BUFFER_SIZE, SocketFlags.None,
new AsyncCallback(ReceiveCallback), so);
}
else
{
Dispatcher.Invoke(() =>
{
Add2ListView(socket.RemoteEndPoint + ": 客户端连接已断开.");
for (int i = ; i < tvRemotes.Items.Count; i++)
{
TreeViewItem tvi = (TreeViewItem)tvRemotes.Items[i];
if ((string)tvi.Tag == socket.RemoteEndPoint.ToString())
{
tvRemotes.Items.Remove(tvi);
socketList.Remove(socket);
return;
}
}
},
DispatcherPriority.Normal); socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
} private void Add2TreeView(string strRemote)
{
TreeViewItem tvi = new TreeViewItem();
tvi.Tag = strRemote;
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Horizontal;
sp.Children.Add(new PackIcon { Kind = PackIconKind.Devices });
sp.Children.Add(new TextBlock { Text = $"{strRemote}" });
tvi.Items.Add(sp);
tvRemotes.Items.Add(tvi);
} private void Add2ListView(string text)
{
TextBlock tb = new TextBlock { Text = text };
lvDebugs.Items.Add(tb);
}
}
}
3.运行效果