1、TCP实现类
internal class TcpServer
{
public Socket ServerSocket { get; set; }
public Dictionary<string,Socket> Sockets { get; set; }= new Dictionary<string,Socket>();
public byte[] SendBuffer { get; set; }
public byte[] ReceiveBuffer { get; set; }
/// <summary>
/// 创建构造函数
/// </summary>
/// <param name="sendBufferLength"></param>
/// <param name="receiveBufferLength"></param>
public TcpServer(int sendBufferLength, int receiveBufferLength)
{
SendBuffer = new byte[sendBufferLength];
ReceiveBuffer = new byte[receiveBufferLength];
}
/// <summary>
/// 启动服务器
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
public void Start(string ip, string port)
{
ServerSocket = CreateSocket(ip, port);
CreateThread();
}
/// <summary>
/// 服务端向指定客户端发送消息
/// </summary>
/// <param name="clientInfo"></param>
/// <param name="data"></param>
public void Send(string clientInfo, byte[] data)
{
Socket socket = Sockets[clientInfo];
socket.Send(data);
}
/// <summary>
/// 创建服务端Socket
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <returns></returns>
private Socket CreateSocket(string ip, string port)
{
Socket socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress address=IPAddress.Parse(ip);
IPEndPoint endPoint=new IPEndPoint(address, int.Parse(port));
socket.Bind(endPoint);
socket.Listen(20);
return socket;
}
/// <summary>
/// 创建监听客户端的线程并启动
/// </summary>
private void CreateThread()
{
Thread watchThread = new Thread(WatchConnection);
watchThread.IsBackground = true;
watchThread.Start();
}
/// <summary>
/// 监听客户端请求
/// </summary>
private void WatchConnection()
{
while (true)
{
Socket clientSocket = null;
try
{
clientSocket = ServerSocket.Accept();
IPEndPoint endPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
string ip= endPoint.Address.ToString();
string port= endPoint.Port.ToString();
Sockets.Add(ip + ":" + port, clientSocket);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
break;
}
ParameterizedThreadStart pts = new ParameterizedThreadStart(ClientReceiver);
Thread clientThread = new Thread(pts);
clientThread.IsBackground = true;
clientThread.Start(clientSocket);
}
}
/// <summary>
///
/// </summary>
/// <param name="socket"></param>
private void ClientReceiver(object socket)
{
Socket clientSocket=socket as Socket;
int ReceiveBufferSize = 1 * 1024;
while (true)
{
int receivedLength = 0;
byte[] buffer = new byte[ReceiveBufferSize];
try
{
List<byte> ls = new List<byte>();
if (clientSocket != null)
{
receivedLength = clientSocket.Receive(buffer);
if (receivedLength > 0)
{
Buffer.BlockCopy(buffer,0, ReceiveBuffer, 0, receivedLength);
string msg = "Receive Success " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
byte[] datas = System.Text.Encoding.UTF8.GetBytes(msg);
clientSocket.Send(datas);
}
}
}catch(Exception ex)
{
Console.WriteLine(ex.ToString());
break;
}
}
}
}
2、页面布局
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="配置" VerticalAlignment="Center"/>
<DockPanel Grid.Row="1">
<DockPanel HorizontalAlignment="Left">
<TextBlock Text="地址" VerticalAlignment="Center" Margin="20 0 10 0"/>
<TextBox x:Name="TextBoxIp" Text="" Width="100" Height="36" VerticalContentAlignment="Center"/>
<TextBlock Text="端口" VerticalAlignment="Center" Margin="20 0 10 0"/>
<TextBox x:Name="TextBoxport" Text="" Width="100" Height="36" VerticalContentAlignment="Center"/>
<Button x:Name="ButtonStart" Content="启动" Width="75" Height="36" Margin="20,0,10,0" Click="ButtonStart_Click"/>
</DockPanel>
<DockPanel HorizontalAlignment="Right">
<TextBlock Text="客户端" VerticalAlignment="Center" Margin="20 0 10 0"/>
<ComboBox x:Name="ComboBoxClient" SelectedValuePath="Key" DisplayMemberPath="Key" Width="200" Height="36" Margin="20 0 10 0" SelectionChanged="ComboBoxClient_SelectionChanged"/>
</DockPanel>
</DockPanel>
<TextBlock Grid.Row="2" Text="接收" VerticalAlignment="Center"/>
<TextBox Grid.Row="3" Name="TextBoxReciver" Text=""/>
<TextBlock Grid.Row="4" Text="发送" VerticalAlignment="Center"/>
<StackPanel Grid.Row="5" Orientation="Horizontal">
<TextBox x:Name="TextBoxSender" Text="" Width="650" Height="36"/>
<Button Content="发送" Click="ButtonSend_CLick" Width="75" Height="36" HorizontalAlignment="Right" Margin="10 0 20 0"/>
</StackPanel>
</Grid>
3、后台代码
TcpServer tcpServer= null;
public MainWindow()
{
InitializeComponent();
tcpServer = new TcpServer(2 * 1024, 2 * 1024);
TextBoxIp.Text = "10.11.10.44";
TextBoxport.Text = "8080";
}
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
string address = this.TextBoxIp.Text;
string[] arr= address.Split('.');
if (arr.Length == 4)
{
foreach(string item in arr)
{
int i=int.Parse(item);
if(i < 0 || i > 255)
{
return;
}
}
}
string port = this.TextBoxport.Text;
int j= int.Parse(port);
if (j < 0)
{
return;
}
ComboBoxClient.ItemsSource = tcpServer.Sockets;
tcpServer.Start(address, port);
}
string currentClient = null;
private void ComboBoxClient_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//currentClient = ComboBoxClient.SelectedValue.ToString();
ComboBox comboBox = sender as ComboBox;
string str = comboBox.SelectedValue.ToString();
if (tcpServer.Sockets.ContainsKey(str))
{
currentClient = str;
}
}
private void ButtonSend_CLick(object sender, RoutedEventArgs e)
{
if (currentClient != null)
{
string str = TextBoxSender.Text;
byte[] bytes=System.Text.Encoding.UTF8.GetBytes(str);
tcpServer.Send(currentClient,bytes);
}
}
4、运行结果