监测tcp连接状态

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 检测tcp连接状态
{
    public class TCPClient
    {
        private TcpClient client;
        private bool connected;
        private EventWaitHandle disconnectEvent;

        public event Action OnConnect;
        public event Action OnReceive;
        public event Action OnDisconnect;

        public TCPClient()
        {
            client = new TcpClient();
            connected = false;
            disconnectEvent = new AutoResetEvent(false);
        }

        public void Connect(string host, int port)
        {
            try
            {
                client = new TcpClient(host, port);
                connected = true;
                OnConnect?.Invoke();
                Listen();
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to connect: {e.Message}");
                Disconnect();
            }
        }

        public void Send(byte[] data)
        {
            try
            {
                NetworkStream stream = client.GetStream();
                stream.Write(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error while sending data: {e.Message}");
                Disconnect();
            }
        }

        public void Disconnect()
        {
            if (connected)
            {
                connected = false;
                client.Close();
                OnDisconnect?.Invoke();
                disconnectEvent.Set();
            }
        }

        private void Listen()
        {
            NetworkStream stream = client.GetStream();
            byte[] buffer = new byte[1024];

            while (connected)
            {
                try
                {
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        Disconnect();
                        break;
                    }
                    byte[] receivedData = new byte[bytesRead];
                    Array.Copy(buffer, receivedData, bytesRead);
                    OnReceive?.Invoke(receivedData);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error while receiving data: {e.Message}");
                    Disconnect();
                }
            }
        }
    }
}

监测tcp连接状态_第1张图片

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;


namespace 检测tcp连接状态
{

    public partial class Form2 : Form
    {
        private TCPClient tcpClient;
        private Thread connectThread;
        public Form2()
        {
            InitializeComponent();

            tcpClient = new TCPClient();

            tcpClient.OnConnect += () =>
            {
                UpdateStatusLabel("Connected");
            };

            tcpClient.OnReceive += (data) =>
            {
                // 处理接收到的数据
                string response1 = Encoding.UTF8.GetString(data, 0, data.Length);

                MessageBox.Show(response1);
            };

            tcpClient.OnDisconnect += () =>
            {
                UpdateStatusLabel("Disconnected");
            };


        }

        private void ConnectButton_Click(object sender, EventArgs e)
        {
            connectThread = new Thread(() => tcpClient.Connect("127.0.0.1", 60000));
            connectThread.Start();
        }

        private void DisconnectButton_Click(object sender, EventArgs e)
        {
            tcpClient.Disconnect();
        }

        private void UpdateStatusLabel(string status)
        {
            if (StatusLabel.InvokeRequired)
            {
                StatusLabel.BeginInvoke((MethodInvoker)(() =>
                {
                    StatusLabel.Text = status;
                }));
            }
            else
            {
                StatusLabel.Text = status;
            }
        }
    }
}

 

你可能感兴趣的:(网络)