目录
一 设计原型
二 后台源码
一 设计原型
二 后台源码
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace 上位机网络通讯
{public partial class Form1 : Form{public Form1(){InitializeComponent();}Socket socket = null;private void hslSwitch1_OnSwitchChanged(object arg1, bool arg2){if (hslSwitch1.SwitchStatus){Task.Run(() =>{socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);socket.Connect("127.0.0.1", 8899);while (true){byte[] bytes = new byte[1024];socket.Receive(bytes);string data = Encoding.UTF8.GetString(bytes);if (data.Length > 0){this.Invoke(new Action<string>(AddData), data);}}});}}private void AddData(string data){dataGridView1.Rows.Add(data, data, data, data, data, data, data, DateTime.Now.ToLongTimeString(), "OK");}}
}