初識Modbus TCP/IP-------------C#編寫Modbus TCP客戶端程式(一)
阿新 • • 發佈:2019-02-02
using System; using System.Windows.Forms; using System.Net.Sockets; using System.Threading; using System.Net; namespace Modbus_TCP_Client { public partial class Form1 : Form { public Socket newclient; public bool Connected; public Thread myThread; public delegate void MyInvoke(string str); public Form1() { InitializeComponent(); } private void exit_Click(object sender, EventArgs e) { Application.Exit(); } public void Connect() { byte[] data = new byte[1024]; string ipadd = serverIP.Text.Trim();//將伺服器IP地址存放在字串 ipadd中 int port = Convert.ToInt32(serverPort.Text.Trim());//將埠號強制為32位整型,存放在port中 //建立一個套接字 IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port); newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //將套接字與遠端伺服器地址相連 try { newclient.Connect(ie); connect.Enabled = false;//使連線按鈕變成虛的,無法點選 Connected = true; } catch (SocketException e) { MessageBox.Show("連線伺服器失敗 " + e.Message); return; } ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg); myThread = new Thread(myThreaddelegate); myThread.Start(); tmSend.Enabled = true;//增加定時傳送需要將此功能開啟 } private void connect_Click_1(object sender, EventArgs e) { Connect(); } } }