C# Socke TCP重连操作
1 using Newtonsoft.Json; 2 using System; 3 using System.Collections.Generic; 4 using System.ComponentModel; 5 using System.Data; 6 using System.Drawing; 7 using System.Linq; 8 using System.Net; 9 using System.Net.Sockets; 10 using System.Text; 11 using System.Threading; 12 using System.Threading.Tasks; 13 using System.Windows.Forms; 14 15 namespace WindowsFormsApp52 16 { 17 public partial class Form1 : Form 18 { 19 public Form1() 20 { 21 InitializeComponent(); 22 } 23 24 private static int flag = 0; 25 System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); 26 static Socket client = null; 27 static IPAddress ip = IPAddress.Parse("127.0.0.1"); 28 static int port = 7000; 29 static IPEndPoint ipe = new IPEndPoint(ip, port); 30 31 private void Button1_Click(object sender, EventArgs e) 32 { 33 // 启动定时器检测连接 34 timer.Enabled = true; 35 timer.Interval = 5000; 36 timer.Tick += Timer_Tick; 37 38 } 39 private bool IsSocketConnected(Socket client, IPEndPoint ipe) 40 { 41 bool blockingState = client.Blocking; 42 43 try 44 { 45 46 string tmpstr = "1"; 47 byte[] data = Encoding.ASCII.GetBytes(tmpstr); 48 client.Blocking = false; 49 50 try 51 { 52 int ii = client.Send(data, data.Length, 0); 53 if (ii > 0) 54 return true; 55 else 56 return false; 57 58 } 59 catch (Exception ex) 60 { 61 flag = (int)SocketStatus.Close; 62 client.Close(); 63 return false; 64 } 65 66 } 67 catch (SocketException e) 68 { 69 // 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的 70 if (e.NativeErrorCode.Equals(10035)) 71 return false; 72 else 73 return false; 74 } 75 finally 76 { 77 client.Blocking = blockingState; // 恢复状态 78 } 79 } 80 private void Timer_Tick(object sender, EventArgs e) 81 { 82 if (client == null) 83 { 84 client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 85 try 86 { 87 client.Connect(ipe); 88 } 89 catch (Exception) 90 { 91 } 92 93 } 94 if (flag != (int)SocketStatus.Start && flag == (int)SocketStatus.Close) 95 { 96 client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 97 try 98 { 99 client.Connect(ipe); 100 } 101 catch (Exception) 102 { } 103 flag = (int)SocketStatus.Other; 104 } 105 106 try 107 { 108 if (IsSocketConnected(client, ipe)) 109 { 110 label2.Text = "已连接"; 111 112 //执行发送TCP的数据处理 113 SendMes(); 114 115 } 116 else 117 { 118 label2.Text = "未连接"; 119 } 120 121 } 122 catch (Exception) 123 { 124 label2.Text = "未连接"; 125 } 126 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace WindowsFormsApp52 8 { 9 public class Status 10 { 11 } 12 13 public enum SocketStatus 14 { 15 /// <summary> 16 /// 程序启动时 17 /// </summary> 18 Start, 19 /// <summary> 20 /// Socket连接断开 21 /// </summary> 22 Close, 23 /// <summary> 24 /// 其他 25 /// </summary> 26 Other 27 28 } 29 }
本文来自博客园,作者:yun5,转载请注明原文链接:https://www.cnblogs.com/yun5/articles/16748154.html

浙公网安备 33010602011771号