以太网通讯

接口开发笔记-WebApi-CSDN博客

以太网常用通讯协议

1、modbus tcp

复制代码
using EasyModbus;
using System;
 
class Program
{
    static void Main(string[] args)
    {
        // 创建Modbus客户端实例
        ModbusClient modbusClient = new ModbusClient("192.168.1.100"); // IP地址
        modbusClient.Port = Modbus.Port.TcpPort(502); // Modbus TCP端口,默认是502
        modbusClient.UnitIdentifier = 1; // Modbus单元标识符,根据你的设备设置
 
        try
        {
            // 连接服务器
            modbusClient.Connect();
 
            // 读取保持寄存器,例如从地址0开始的4个寄存器
            ushort[] registers = modbusClient.ReadHoldingRegisters(0, 4);
            Console.WriteLine("Read registers:");
            foreach (ushort reg in registers)
            {
                Console.WriteLine(reg);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        finally
        {
            // 断开连接
            if (modbusClient.Connected)
            {
                modbusClient.Disconnect();
            }
        }
    }
}

2.Socket编程

复制代码
//示例代码:TCP客户端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
class TCPClientExample
{
    static void Main()
    {
        // 创建Socket对象
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        
        // 连接到服务器
        clientSocket.Connect("127.0.0.1", 12345); // 服务器IP和端口
        
        // 发送数据
        string message = "Hello, Server!";
        byte[] byteData = Encoding.ASCII.GetBytes(message);
        clientSocket.Send(byteData);
        
        // 接收数据
        byte[] receivedBytes = new byte[1024];
        int bytesReceived = clientSocket.Receive(receivedBytes);
        string response = Encoding.ASCII.GetString(receivedBytes, 0, bytesReceived);
        Console.WriteLine("Received: " + response);
        
        // 关闭连接
        clientSocket.Shutdown(SocketShutdown.Both);
        clientSocket.Close();
    }
}

//示例代码:TCP服务器

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
 
class TCPServerExample
{
    public static void StartListening()
    {
        // 创建Socket对象
        Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12345); // 监听端口12345
        serverSocket.Bind(localEndPoint); // 绑定端口
        serverSocket.Listen(10); // 最大连接数10
        Console.WriteLine("Server started...");
        
        while (true)
        {
            Socket clientSocket = serverSocket.Accept(); // 接受客户端连接请求
            Thread receiveThread = new Thread(new ParameterizedThreadStart(ReceiveMessage)); // 开启新线程处理客户端请求
            receiveThread.Start(clientSocket); // 启动线程处理客户端请求
        }
    }
    
    private static void ReceiveMessage(object clientSocketObj)
    {
        Socket clientSocket = (Socket)clientSocketObj;
        byte[] buffer = new byte[1024]; // 接收缓冲区
        int bytesReceived = clientSocket.Receive(buffer); // 接收数据长度
        string data = Encoding.ASCII.GetString(buffer, 0, bytesReceived); // 将字节转换为字符串
        Console.WriteLine("Received: " + data); // 输出接收到的数据
        string response = "ACK"; // 响应消息
        byte[] byteData = Encoding.ASCII.GetBytes(response); // 将字符串转换为字节数组并发送回去
        clientSocket.Send(byteData); // 发送响应数据到客户端
        clientSocket.Shutdown(SocketShutdown.Both); // 关闭连接
        clientSocket.Close(); // 关闭套接字对象
    }
    
    static void Main() { StartListening(); }
}
相关推荐
Azhao110617 小时前
商城产品详情页的客服咨询在哪里设置详解:从入门到实战全攻略
sqlite
ggabb1 天前
战斗机器人的发展与战争伦理影响
sqlite
鹏子训2 天前
AI记忆新思路:用SQLite替代向量数据库,去EMBEDDINGS化,谷歌开源Google Always On Memory Agent
数据库·人工智能·sqlite·embedding
Muyuan19982 天前
25.Paper RAG Agent 优化记录:上传反馈、计算器安全与 Chunk 参数调整
python·安全·django·sqlite·fastapi
code_pgf7 天前
sqlite数据库cmakelist.txt编译
数据库·sqlite
_F_y7 天前
SQLite3的基础使用
jvm·数据库·sqlite
IntMainJhy8 天前
【flutter for open harmony】第三方库 Flutter 二维码生成的鸿蒙化适配与实战指南
数据库·flutter·华为·sqlite·harmonyos
IntMainJhy8 天前
【flutter for open harmony】第三方库Flutter 国际化多语言的鸿蒙化适配与实战指南
数据库·flutter·华为·sqlite·harmonyos
IntMainJhy8 天前
【flutter for open harmony】Flutter SQLite 本地数据库的鸿蒙化适配与实战指南
数据库·flutter·sqlite
北冥有羽Victoria9 天前
Django Auth组件完整版教程:从原理到项目落地
大数据·服务器·数据库·后端·python·django·sqlite