wenxiangchao
2026-11-02 9d1660270272180cd71147d6ddd53d1382643d2e
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
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
namespace CellStepSender
{
    public class TcpClientTool3
    {
        private string _ip;
        private int _port;
        private bool _isConnected = false; // 是否连接
        private Socket _clientSocket; // 套接字
 
        public event EventHandler<string> ExecuteMessageChanged;
 
        public TcpClientTool3(string ip, int port)
        {
            this._ip = ip;
            this._port = port;
        }
 
        public void Connect()
        {
            try
            {
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipaddress = IPAddress.Parse(this._ip);
                IPEndPoint endpoint = new IPEndPoint(ipaddress, _port);
                _clientSocket.Connect(endpoint);
                _isConnected = true;
            }
            catch (Exception ex)
            {
                _clientSocket.Dispose();
                _isConnected = false;
                throw ex;
            }
        }
 
        public void Disconnect()
        {
            _clientSocket.Dispose();
        }
 
        public void Send(string data)
        {
            byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(data);
            lock (this)
            {
                _clientSocket.Send(arrClientSendMsg);
            }
        }
 
        public bool SendStep(
            string ip, int port,
            int ovenIndex, int cellIndex, string step, string value, string limitUp,
            string limitDown, string unit, string result, string updateTime, out string errorMsg)
        {
 
            errorMsg = null;
            try
            {
                if (!_isConnected)
                {
                    errorMsg = "Not Connected";
                    return false;
                }
 
                string msg = $"{ovenIndex};{cellIndex};{step},{value},{limitUp},{limitDown},{unit},{result},{updateTime}\n";
                Send(msg);
                return true;
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                return false;
            }
        }
    }
}