C# WinForm的TCP/IP通信窗口应用程序

360影视 国产动漫 2025-03-01 00:33 6

摘要:stream.Write(buffer, 0, buffer.Length);

using System;

using System.Net.Sockets;

using System.Text;

using System.Windows.Forms;

namespace MotorControlApp

{

public partial class Form1 : Form

{

// TCP通信相关

private TcpClient client;

private NetworkStream stream;

private bool isConnected = false;

// 时间显示

private Timer clockTimer = new Timer;

public Form1

{

InitializeComponent;

InitializeComponents;

}

private void InitializeComponents

{

// 控件初始化

txtIP.Text = "192.168.1.100";

txtPort.Text = "8080";

btnConnect.Text = "连接";

// 时钟定时器

clockTimer.Interval = 1000;

clockTimer.Tick += UpdateTime;

clockTimer.Start;

}

}

}

控件类型Name属性功能说明TextBoxtxtIPIP地址输入TextBoxtxtPort端口号输入ButtonbtnConnect连接/断开按钮ButtonbtnUp电机上升控制ButtonbtnDown电机下降控制RichTextBoxtxtStatus故障提示与状态显示LabellblTime当前时间显示

// 连接按钮事件

private void btnConnect_Click(object sender, EventArgs e)

{

if (!isConnected)

{

try

{

client = new TcpClient;

client.Connect(txtIP.Text, int.Parse(txtPort.Text));

stream = client.GetStream;

isConnected = true;

btnConnect.Text = "断开";

AppendStatus("连接成功");

}

catch (Exception ex)

{

AppendStatus($"连接失败: {ex.Message}");

}

}

else

{

client.Close;

isConnected = false;

btnConnect.Text = "连接";

AppendStatus("已断开连接");

}

}

// 发送控制指令

private void SendCommand(byte command)

{

if (isConnected)

{

try

{

byte buffer = new byte { command };

stream.Write(buffer, 0, buffer.Length);

AppendStatus($"发送指令: 0x{command:X2}");

}

catch (Exception ex)

{

AppendStatus($"发送失败: {ex.Message}");

}

}

}

// 按钮事件绑定

private void btnUp_Click(object sender, EventArgs e) => SendCommand(0x01); // 上升指令

private void btnDown_Click(object sender, EventArgs e) => SendCommand(0x02); // 下降指令

// 更新时间显示

private void UpdateTime(object sender, EventArgs e)

{

lblTime.Text = DateTime.Now.ToString("HH:mm:ss");

}

// 状态提示追加

private void AppendStatus(string message)

{

txtStatus.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\n");

txtStatus.ScrollToCaret;

}

添加输入验证:

private bool ValidateIPPort

{

if (!IPAddress.TryParse(txtIP.Text, out _)) {

MessageBox.Show("无效IP地址");

return false;

}

if (!int.TryParse(txtPort.Text, out _)) {

MessageBox.Show("无效端口号");

return false;

}

return true;

}

添加连接状态检查:

private void SendCommand(byte command)

{

if (!isConnected) {

AppendStatus("请先建立连接");

return;

}

// ...原有发送逻辑

}

来源:视未来

相关推荐