Skip to content

Commit

Permalink
add: tcp客户端ssl功能, close #125
Browse files Browse the repository at this point in the history
  • Loading branch information
chenxuuu committed May 30, 2023
1 parent 1a1287b commit 884a3a4
Show file tree
Hide file tree
Showing 2 changed files with 221 additions and 58 deletions.
149 changes: 100 additions & 49 deletions llcom/Pages/SocketClientPage.xaml
Original file line number Diff line number Diff line change
@@ -1,72 +1,123 @@
<Page x:Class="llcom.Pages.SocketClientPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:llcom.Pages"
xmlns:adonisExtensions="clr-namespace:AdonisUI.Extensions;assembly=AdonisUI"
adonisExtensions:RippleExtension.FadeInDuration="0"
adonisExtensions:RippleExtension.FadeOutDuration="0"
mc:Ignorable="d"
d:DesignHeight="440" d:DesignWidth="400"
Title="SocketClientPage"
Loaded="Page_Loaded">
<Page
x:Class="llcom.Pages.SocketClientPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:adonisExtensions="clr-namespace:AdonisUI.Extensions;assembly=AdonisUI"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:llcom.Pages"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="SocketClientPage"
adonisExtensions:RippleExtension.FadeInDuration="0"
adonisExtensions:RippleExtension.FadeOutDuration="0"
d:DesignHeight="440"
d:DesignWidth="400"
Loaded="Page_Loaded"
mc:Ignorable="d">
<Page.Resources>
<local:boolConnected x:Key="boolConnectedConverter"/>
<local:boolNot x:Key="boolNotConverter"/>
<local:boolVisibe x:Key="boolVisibeConverter"/>
<local:boolConnected x:Key="boolConnectedConverter" />
<local:boolNot x:Key="boolNotConverter" />
<local:boolVisibe x:Key="boolVisibeConverter" />
</Page.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<Grid IsEnabled="{Binding Changeable}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{DynamicResource TcpServerAddr}" VerticalAlignment="Center"/>
<TextBox Name="ServerTextBox" Text="{Binding tcpClientServer}" Grid.Column="1" Margin="5,0"/>
<TextBlock Text="{DynamicResource TcpServerPort}" Grid.Row="1" VerticalAlignment="Center"/>
<Grid Grid.Column="1" Grid.Row="1" Margin="0,3">
<TextBlock VerticalAlignment="Center" Text="{DynamicResource TcpServerAddr}" />
<TextBox
Name="ServerTextBox"
Grid.Column="1"
Margin="5,0"
Text="{Binding tcpClientServer}" />
<TextBlock
Grid.Row="1"
VerticalAlignment="Center"
Text="{DynamicResource TcpServerPort}" />
<Grid
Grid.Row="1"
Grid.Column="1"
Margin="0,3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Name="PortTextBox" Text="{Binding tcpClientPort}" Margin="5,0"/>
<TextBlock Text="{DynamicResource TcpServerProtocol}" VerticalAlignment="Center" Grid.Column="1"/>
<ComboBox Name="ProtocolTypeComboBox" Grid.Column="2" Margin="5,0" SelectedIndex="{Binding tcpClientProtocolType}">
<ComboBoxItem Content="TCP"/>
<ComboBoxItem Content="UDP"/>
<TextBox
Name="PortTextBox"
Margin="5,0"
Text="{Binding tcpClientPort}" />
<TextBlock
Grid.Column="1"
VerticalAlignment="Center"
Text="{DynamicResource TcpServerProtocol}" />
<ComboBox
Name="ProtocolTypeComboBox"
Grid.Column="2"
Margin="5,0"
SelectedIndex="{Binding tcpClientProtocolType}">
<ComboBoxItem Content="TCP" />
<ComboBoxItem Content="UDP" />
<ComboBoxItem Content="TCP SSL" />
</ComboBox>
</Grid>
</Grid>
<Button Name="ConnectButton" Content="{DynamicResource ConnectButton}" Grid.Column="1" Click="ConnectButton_Click"/>
<Button Name="DisconnectButton" Content="{DynamicResource DisconnectButton}" Grid.Column="1" Click="DisconnectButton_Click"
Visibility="{Binding IsConnected,Converter={StaticResource boolVisibeConverter}}"/>
<Button
Name="ConnectButton"
Grid.Column="1"
Click="ConnectButton_Click"
Content="{DynamicResource ConnectButton}" />
<Button
Name="DisconnectButton"
Grid.Column="1"
Click="DisconnectButton_Click"
Content="{DynamicResource DisconnectButton}"
Visibility="{Binding IsConnected, Converter={StaticResource boolVisibeConverter}}" />
</Grid>

<StackPanel Orientation="Horizontal" Grid.Row="1" Grid.ColumnSpan="3">
<TextBlock Text="{DynamicResource ToSendDataTextBlock}" VerticalAlignment="Center"/>
<CheckBox Content="Hex" IsChecked="{Binding HexMode}" Grid.Row="2" HorizontalAlignment="Left" Margin="2"
VerticalAlignment="Center"/>
<StackPanel
Grid.Row="1"
Grid.ColumnSpan="3"
Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="{DynamicResource ToSendDataTextBlock}" />
<CheckBox
Grid.Row="2"
Margin="2"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Content="Hex"
IsChecked="{Binding HexMode}" />
</StackPanel>
<TextBox Name="ToSendTextBox" VerticalContentAlignment="Top" TextWrapping="Wrap" AcceptsReturn="True"
VerticalScrollBarVisibility="Auto" FontFamily="Consolas" Grid.Row="2" Margin="0,3,0,0"/>
<Button Name="SendButton" Content="{DynamicResource NetSendDataButton}" Grid.Row="3" HorizontalAlignment="Right" Margin="0,5,0,0"
Click="SendButton_Click"/>
<TextBox
Name="ToSendTextBox"
Grid.Row="2"
Margin="0,3,0,0"
VerticalContentAlignment="Top"
AcceptsReturn="True"
FontFamily="Consolas"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto" />
<Button
Name="SendButton"
Grid.Row="3"
Margin="0,5,0,0"
HorizontalAlignment="Right"
Click="SendButton_Click"
Content="{DynamicResource NetSendDataButton}" />
</Grid>
</Page>
130 changes: 121 additions & 9 deletions llcom/Pages/SocketClientPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
using llcom.LuaEnv;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
Expand All @@ -15,6 +19,7 @@
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static llcom.Pages.SocketClientPage;

namespace llcom.Pages
{
Expand All @@ -38,7 +43,7 @@ public SocketClientPage()
public bool HexMode { get; set; } = false;

//暂存一个对象
Socket socketNow = null;
SocketObj socketNow = null;

private void Page_Loaded(object sender, RoutedEventArgs e)
{
Expand Down Expand Up @@ -106,8 +111,8 @@ private void ConnectButton_Click(object sender, RoutedEventArgs e)
}
ipe = new IPEndPoint(ip, int.Parse(PortTextBox.Text));
s = new Socket(ipe.AddressFamily,
ProtocolTypeComboBox.SelectedIndex == 0 ? SocketType.Stream : SocketType.Dgram,
ProtocolTypeComboBox.SelectedIndex == 0 ? ProtocolType.Tcp : ProtocolType.Udp);
ProtocolTypeComboBox.SelectedIndex == 1 ? SocketType.Dgram : SocketType.Stream,
ProtocolTypeComboBox.SelectedIndex == 1 ? ProtocolType.Udp : ProtocolType.Tcp);
}
catch(Exception ex)
{
Expand All @@ -118,12 +123,15 @@ private void ConnectButton_Click(object sender, RoutedEventArgs e)
ShowData("📢 Connecting......");
try
{
StateObject so = new StateObject();
so.isSSL = ProtocolTypeComboBox.SelectedIndex == 2;
s.BeginConnect(ipe, new AsyncCallback((r) =>
{
var s = (Socket)r.AsyncState;
if (s.Connected)
{
socketNow = s;
if (!so.isSSL)
socketNow = new SocketObj(s);
IsConnected = true;
ShowData("✔ Server connected");
}
Expand All @@ -134,9 +142,38 @@ private void ConnectButton_Click(object sender, RoutedEventArgs e)
return;
}
StateObject so = new StateObject();
so.workSocket = s;
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(Read_Callback), so);
if(so.isSSL)
{
var networkStream = new NetworkStream(s);
var ssl = new SslStream(
networkStream,
false,
new RemoteCertificateValidationCallback((_, _, _, _) => true),
null);
so.workStream = ssl;
try
{
ssl.AuthenticateAsClient("llcom tcp ssl client");
}
catch(Exception ssle)
{
ShowData($"❗ SSL error {ssle.Message}");
socketNow = null;
IsConnected = false;
Changeable = true;
s.Close();
s.Dispose();
ShowData("❌ Server disconnected");
return;
}
socketNow = new SocketObj(ssl);
ssl.BeginRead(so.buffer, 0, StateObject.BUFFER_SIZE, new AsyncCallback(Read_Callback), so);
}
else
{
so.workSocket = s;
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(Read_Callback), so);
}
}), s);
}
catch (Exception ex)
Expand All @@ -150,6 +187,42 @@ private void ConnectButton_Click(object sender, RoutedEventArgs e)
public void Read_Callback(IAsyncResult ar)
{
StateObject so = (StateObject)ar.AsyncState;

if (so.isSSL)//ssl连接
{
var ssl = so.workStream;
try
{
int read = ssl.EndRead(ar);

if (read > 0)
{
var buff = new byte[read];
for (int i = 0; i < buff.Length; i++)
buff[i] = so.buffer[i];
DataRecived?.Invoke(null, buff);
ssl.BeginRead(so.buffer, 0, StateObject.BUFFER_SIZE,
new AsyncCallback(Read_Callback), so);
}
else//断了?
{
try
{
ssl.Close();
ssl.Dispose();
}
catch { }
socketNow = null;
IsConnected = false;
Changeable = true;
ShowData("❌ Server disconnected");
}
}
catch { }

return;
}

Socket s = so.workSocket;
try
{
Expand Down Expand Up @@ -189,7 +262,6 @@ private void DisconnectButton_Click(object sender, RoutedEventArgs e)
try
{
socketNow.Close();
socketNow.Dispose();
}
catch { }
socketNow = null;
Expand Down Expand Up @@ -227,8 +299,48 @@ private bool Send(byte[] buff)
public class StateObject
{
public Socket workSocket = null;
public const int BUFFER_SIZE = 2048;
public SslStream workStream = null;
public const int BUFFER_SIZE = 204800;
public byte[] buffer = new byte[BUFFER_SIZE];
public bool isSSL = false;
}

public class SocketObj
{
Socket socket;
SslStream sslStream;
public SocketObj(Socket s)
{
socket = s;
}
public SocketObj(SslStream ssl)
{
sslStream = ssl;
}
public void Send(byte[] buff)
{
if (socket != null)
socket.Send(buff);
else if (sslStream != null)
{
sslStream.Write(buff);
}

}

public void Close()
{
if (socket != null)
{
socket.Close();
socket.Dispose();
}
else if (sslStream != null)
{
sslStream.Close();
sslStream.Dispose();
}
}
}
}
}

0 comments on commit 884a3a4

Please sign in to comment.