目录
一 设计原型
二 后台源码
using System;
using System.Drawing;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 上位机网络通讯
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
uiLight1.OnColor = Color.Red;
timer1.Enabled = true;
timer1.Tick += Timer1_Tick;
}
private void Timer1_Tick(object sender, EventArgs e)
{
this.Invoke(new Action(Times));
}
Socket socket = null;
int Count = 0;
private void hslSwitch1_OnSwitchChanged(object arg1, bool arg2)
{
if (hslSwitch1.SwitchStatus)
{
uiLight1.OnColor = Color.Green;
Task.Run(() =>
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("127.0.0.1", 8899);
while (true)
{
if (hslSwitch1.SwitchStatus)
{
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);
}
}
}
});
}
else
{
uiLight1.OnColor = Color.Red;
}
}
private void AddData(string data)
{
dataGridView1.Rows.Add(data, data, data, data, data, data, data, DateTime.Now.ToLongTimeString(), "OK");
Count++;
uiDigitalLabel1.Value = Count;
}
private void Times()
{
uiTextBox1.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
}
}