wxr
2020-11-04 e6a26ee148587327478d9a82624a820c907b6e16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
 
namespace HDL_ON.DriverLayer
{
    public class Control_TcpClient
    {
        //声明IP,端口,和一个用来连接的Socket
        public string _ip;
 
        private TcpClient _tcpClient;
 
        //创建一个委托,用来满足其他类调用
        public delegate void DelegateMessage(byte[] bytes);
        public event DelegateMessage OnmessageEvent;
 
        /// <summary>
        /// 构造函数
        /// </summary>
        public Control_TcpClient(string serverIp)
        {
            _ip = serverIp;
        }
 
        //TCP连接
        public bool Connect(int _port = 8586)
        {
            if (string.IsNullOrEmpty(_ip) || _port == 0)
            {
                return false;
            }
            _tcpClient = new TcpClient();
            try
            {
                _tcpClient.Connect(IPAddress.Parse(_ip), _port);
                Task.Run(new Action(ReceiveMessage));//开启线程,不停接收消息
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return true;//返回连接状态
        }
        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <returns></returns>
        public bool Close()
        {
            if (_tcpClient == null)
                return true;
            _tcpClient.Close();
            _tcpClient = null;
            return true;
        }
 
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="bytes">需要发送的字节</param>
        public void SendMessage(byte[] bytes)
        {
            NetworkStream networkStream = _tcpClient.GetStream();
            networkStream.Write(bytes, 0, bytes.Length);
        }
 
        //接收消息
        public void ReceiveMessage()
        {
            NetworkStream networkStream = _tcpClient.GetStream();
            while (true)
            {
                byte[] buffer = new byte[8];
                int size = networkStream.Read(buffer, 0, buffer.Length);
                OnmessageEvent?.Invoke(buffer);
            }
        }
 
    }
}