TCPIP串口通讯例子:
winform界面
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
namespace TCPIP
{
public partial class Form1 : Form
{
private TcpClient client;
private NetworkStream stream;
private Thread receiveThread;
private System.Timers.Timer sendTimer; // 创建Timer对象
public Form1()
{
InitializeComponent();
sendTimer = new System.Timers.Timer(); // 实例化Timer对象
sendTimer.Interval = 300; // 设置间隔时间为300毫秒
sendTimer.Elapsed += SendData; // 为Elapsed事件添加处理方法
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
// 连接到服务器
client = new TcpClient("192.168.0.22", 80);
stream = client.GetStream();
// 启动接收线程
receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.Start();
MessageBox.Show("已连接到服务器");
}
catch (Exception ex)
{
MessageBox.Show("无法连接到服务器:" + ex.Message);
}
}
private void btnSend_Click(object sender, EventArgs e)
{
if (client == null || !client.Connected)
{
MessageBox.Show("未连接到服务器");
return;
}
// 启动定时器
sendTimer.Start();
}
private void SendData(object sender, ElapsedEventArgs e)
{
if (client == null || !client.Connected)
{
MessageBox.Show("未连接到服务器");
return;
}
// 发送数据给服务器
byte[] data2 = new byte[100];
for (int i = 0; i < 100; i++)
{
data2[i] = (byte)i;
}
string message = "";
for (int i = 0; i < data2.Length; i+=2)
{
message += Convert.ToString( data2[i]) + Convert.ToString(data2[i+1])+" ";
}
byte[] data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
}
private void ReceiveData()
{
while (true)
{
try
{
// 读取服务器返回的数据
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0) return; // 连接已关闭
string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
string ad = receivedData.Replace(" ", "");
string b = "";
string a = "";
string c = "";
for (int i = 0; i < 10; i++)
{
a += ad[i]+" ";
}
for (int j = 10; j < ad.Length - 1; j += 2)
{
b += ad.Substring(j, 2) + " ";
}
c = a + b;
Invoke((Action)(() => txtMessage.Text += "服务器:" + c));
}
catch
{
MessageBox.Show("连接已断开,请重新连接!", "连接断开");
return;
}
}
}
}
}