Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在tcp client小工具中添加重连机制 #166

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions llcom/Model/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,11 @@ public void SetQuickListNameNow(string name)
private int _tcpServerPort = 2333;
public int tcpServerPort { get { return _tcpServerPort; } set { _tcpServerPort = value; Save(); } }

private bool _tcpReconnect = false;
public bool tcpReconnect { get { return _tcpReconnect; } set { _tcpReconnect = value; Save(); } }
private int _tcpReconnectInterval = 5;
public int tcpReconnectInterval { get { return _tcpReconnectInterval; } set { _tcpReconnectInterval = value; Save(); } }

private int _udpServerPort = 2333;
public int udpServerPort { get { return _udpServerPort; } set { _udpServerPort = value; Save(); } }

Expand Down
32 changes: 28 additions & 4 deletions llcom/Pages/SocketClientPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
</Page.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
Expand Down Expand Up @@ -87,7 +88,7 @@
Grid.Column="1"
Click="DisconnectButton_Click"
Content="{DynamicResource DisconnectButton}"
Visibility="{Binding IsConnected, Converter={StaticResource boolVisibeConverter}}" />
Visibility="{Binding NeedDisconnected, Converter={StaticResource boolVisibeConverter}}" />
</Grid>

<StackPanel
Expand All @@ -96,16 +97,39 @@
Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="{DynamicResource ToSendDataTextBlock}" />
<CheckBox
Grid.Row="2"
Margin="2"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Content="Hex"
IsChecked="{Binding HexMode}" />
</StackPanel>
<CheckBox
Name="NeedReconnect"
Grid.Row="2"
Grid.ColumnSpan="3"
Margin="2,4,2,2"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Content="{DynamicResource TcpReconnect}"
IsChecked="{Binding tcpReconnect}" />
<StackPanel
Grid.Row="2"
HorizontalAlignment="Right"
Orientation="Horizontal">
<TextBlock
VerticalAlignment="Center"
Text="{DynamicResource TcpReconnectInterval}" />
<TextBox
x:Name="ReconnectInterval"
Text="{Binding tcpReconnectInterval, UpdateSourceTrigger=PropertyChanged}"
Width="100"
VerticalAlignment="Center"
IsEnabled="{Binding ElementName=NeedReconnect,Path=IsChecked}"
PreviewTextInput="Reconnect_TextInputCheck" Margin="5,0,0,0"/>
</StackPanel>
<TextBox
Name="ToSendTextBox"
Grid.Row="2"
Grid.Row="3"
Margin="0,3,0,0"
VerticalContentAlignment="Top"
AcceptsReturn="True"
Expand All @@ -114,7 +138,7 @@
VerticalScrollBarVisibility="Auto" />
<Button
Name="SendButton"
Grid.Row="3"
Grid.Row="4"
Margin="0,5,0,0"
HorizontalAlignment="Right"
Click="SendButton_Click"
Expand Down
76 changes: 68 additions & 8 deletions llcom/Pages/SocketClientPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public SocketClientPage()
//收到消息的事件
public event EventHandler<byte[]> DataRecived;
public bool IsConnected { get; set; } = false;
public bool NeedDisconnected { get; set; } = false;

//是否可更改服务器信息
public bool Changeable { get; set; } = true;
public bool HexMode { get; set; } = false;
Expand All @@ -56,6 +58,8 @@ private void Page_Loaded(object sender, RoutedEventArgs e)
ServerTextBox.DataContext = Tools.Global.setting;
PortTextBox.DataContext = Tools.Global.setting;
ProtocolTypeComboBox.DataContext = Tools.Global.setting;
ReconnectInterval.DataContext = Tools.Global.setting;
NeedReconnect.DataContext = Tools.Global.setting;

//收到消息显示
DataRecived += (_, buff) =>
Expand Down Expand Up @@ -90,10 +94,12 @@ private void ShowData(string title, byte[] data = null, bool send = false)
});
}

private void ConnectButton_Click(object sender, RoutedEventArgs e)
private System.Timers.Timer reconnectTimer = null;
private void Reconnect()
{
if (!Changeable)
if (!Changeable || IsConnected)
return;

IPEndPoint ipe = null;
Socket s = null;
try
Expand All @@ -111,10 +117,10 @@ private void ConnectButton_Click(object sender, RoutedEventArgs e)
}
ipe = new IPEndPoint(ip, int.Parse(PortTextBox.Text));
s = new Socket(ipe.AddressFamily,
ProtocolTypeComboBox.SelectedIndex == 1 ? SocketType.Dgram : SocketType.Stream,
ProtocolTypeComboBox.SelectedIndex == 1 ? SocketType.Dgram : SocketType.Stream,
ProtocolTypeComboBox.SelectedIndex == 1 ? ProtocolType.Udp : ProtocolType.Tcp);
}
catch(Exception ex)
catch (Exception ex)
{
ShowData($"❗ Server information error {ex.Message}");
Changeable = true;
Expand All @@ -133,6 +139,7 @@ private void ConnectButton_Click(object sender, RoutedEventArgs e)
if (!so.isSSL)
socketNow = new SocketObj(s);
IsConnected = true;
NeedDisconnected = true;
ShowData("✔ Server connected");
}
else
Expand All @@ -142,24 +149,26 @@ private void ConnectButton_Click(object sender, RoutedEventArgs e)
return;
}

if(so.isSSL)
if (so.isSSL)
{
var networkStream = new NetworkStream(s);
var ssl = new SslStream(
networkStream,
false,
new RemoteCertificateValidationCallback((_, _, _, _) => true),
null);
new RemoteCertificateValidationCallback((_, _, _, _) => true),
null);
so.workStream = ssl;
try
{
ssl.AuthenticateAsClient("llcom tcp ssl client");
}
catch(Exception ssle)
catch (Exception ssle)
{
ShowData($"❗ SSL error {ssle.Message}");
socketNow = null;
IsConnected = false;
if (!Tools.Global.setting.tcpReconnect)
NeedDisconnected = false;
Changeable = true;
s.Close();
s.Dispose();
Expand All @@ -184,6 +193,37 @@ private void ConnectButton_Click(object sender, RoutedEventArgs e)
}
}

private void ConnectButton_Click(object sender, RoutedEventArgs e)
{
if (Tools.Global.setting.tcpReconnect)
{
reconnectTimer = new System.Timers.Timer(Tools.Global.setting.tcpReconnectInterval * 1000);
reconnectTimer.Elapsed += (_, _) =>
{
if (!IsConnected)
{
Dispatcher.Invoke(() =>
{
Reconnect();
});
}
};
reconnectTimer.AutoReset = true;
reconnectTimer.Enabled = true;
NeedDisconnected = true;
}
else
{
if (reconnectTimer != null)
{
reconnectTimer.Stop();
reconnectTimer.Dispose();
reconnectTimer = null;
}
}
Reconnect();
}

public void Read_Callback(IAsyncResult ar)
{
StateObject so = (StateObject)ar.AsyncState;
Expand Down Expand Up @@ -214,6 +254,8 @@ public void Read_Callback(IAsyncResult ar)
catch { }
socketNow = null;
IsConnected = false;
if (!Tools.Global.setting.tcpReconnect)
NeedDisconnected = false;
Changeable = true;
ShowData("❌ Server disconnected");
}
Expand Down Expand Up @@ -248,13 +290,23 @@ public void Read_Callback(IAsyncResult ar)
catch { }
socketNow = null;
IsConnected = false;
if (!Tools.Global.setting.tcpReconnect)
NeedDisconnected = false;
Changeable = true;
ShowData("❌ Server disconnected");
}
}
catch { }
}

private void Reconnect_TextInputCheck(object sender, TextCompositionEventArgs e)
{
if (!int.TryParse(e.Text, out int num) || num < 0 || num > 120)
{
e.Handled = true;
}
}

private void DisconnectButton_Click(object sender, RoutedEventArgs e)
{
if(socketNow != null)
Expand All @@ -269,6 +321,14 @@ private void DisconnectButton_Click(object sender, RoutedEventArgs e)
Changeable = true;
ShowData("❌ Server disconnected");
}

NeedDisconnected = false;
if (reconnectTimer != null)
{
reconnectTimer.Stop();
reconnectTimer.Dispose();
reconnectTimer = null;
}
}

private void SendButton_Click(object sender, RoutedEventArgs e)
Expand Down
2 changes: 2 additions & 0 deletions llcom/languages/en-US.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@
<system:String x:Key="CreateTcpIpv6Button">Test TCP (ipv6)</system:String>
<system:String x:Key="DisconnectButton">Disconnect</system:String>
<system:String x:Key="ConnectButton">Connect</system:String>
<system:String x:Key="TcpReconnect">Auto Reconnect</system:String>
<system:String x:Key="TcpReconnectInterval">Reconnect Interval:</system:String>
<system:String x:Key="TcpServerAddr">Server address</system:String>
<system:String x:Key="TcpServerPort">Server port</system:String>
<system:String x:Key="TcpServerProtocol">Protocol</system:String>
Expand Down
2 changes: 2 additions & 0 deletions llcom/languages/zh-CN.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@
<system:String x:Key="CreateTcpIpv6Button">测试TCP (ipv6)</system:String>
<system:String x:Key="DisconnectButton">断开</system:String>
<system:String x:Key="ConnectButton">连接</system:String>
<system:String x:Key="TcpReconnect">自动重连</system:String>
<system:String x:Key="TcpReconnectInterval">重连间隔:</system:String>
<system:String x:Key="TcpServerAddr">服务器地址</system:String>
<system:String x:Key="TcpServerPort">服务器端口</system:String>
<system:String x:Key="TcpServerProtocol">协议</system:String>
Expand Down