C#与FX5U进行Socket通信

实现效果

实现步骤:

注意:详细的参数这里就不说明了,自己网上搜即可;

打开GX Works3 创建FX5U项目

系统参数设置PLC的具体型号(我有实物PLC)

设置IP及组态参数

添加通讯设备(这里PLC做客户端,因此添加:Active连接设备);

设置PLC的端口号、服务器IP、服务器端口号;

当前添加的设备No为1,记住这个参数,后面程序要输入;

配置完后点击应用并下载到PLC,下载完要重启PLC;

下面不废话,直接上PLC程序;

重点:

在线监控数据

监控D1300是通讯接收数据的起始地址,同时它还存储对方使用了多少个字节发送数据过来;那么我们要截取数据就要从D1301及以后开始截;

还看到PC只发了5个字符,但是收到却多了一位(发:SN123;收:SN1239);那么就要处理一下;把多余的字符删掉;

本项目案例把收到的数据又传回给PC;经过上面的处理已经拿到完整的数据了,然后置位一下M11就能把数据发给PC,注意每次发送都要触发一下M11,可以自己改成自动发送;

C#部分

创建一个页面 SocketPage.xaml

页面代码

<Page x:Class="WpfApp4.Views.SocketPage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfApp4.Views"mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="650"Title="SocketPage" ><Grid><Grid.ColumnDefinitions><ColumnDefinition/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="35"/><RowDefinition Height="35"/><RowDefinition Height="35"/><RowDefinition/></Grid.RowDefinitions><StackPanel Orientation="Horizontal" Grid.Row="0"><Border Height="30" Width="100" Background="White"><TextBlock Text="状态显示"  FontSize="20"   VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Black"/></Border><Border Height="30" Width="500" Background="#FF0ABEFF"><TextBlock Text="欢迎使用该软件" x:Name="txtb_serverData" FontSize="20"   VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="White"/></Border></StackPanel><StackPanel Orientation="Horizontal" Grid.Row="1"><Border Height="30" Width="100" Background="White"><TextBlock Text="读取信息"  FontSize="20"   VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Black"/></Border><Border Height="30" Width="500" Background="#FF0ABEFF"><TextBlock Text="------" x:Name="txtb_reData" FontSize="20"   VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="White"/></Border></StackPanel><StackPanel Orientation="Horizontal" Grid.Row="2"><Border Height="30" Width="100" Background="White"><TextBlock Text="连接设备"  FontSize="20"   VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Black"/></Border><Border Height="30" Width="500" Background="#FF0ABEFF"><TextBlock Text="127.0.0.0:888" x:Name="txtb_ConnentDevice" FontSize="20"   VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="White"/></Border></StackPanel><StackPanel Orientation="Horizontal" Grid.Row="3"><GroupBox Header="服务器与PLC通讯" Width="250" Height="150"  FontSize="20" BorderBrush="#FF0ABEFF" BorderThickness="2"><Grid><Grid.ColumnDefinitions><ColumnDefinition/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><StackPanel VerticalAlignment="Center"   Orientation="Horizontal"  Grid.Row="0"><Border HorizontalAlignment="Left" ><TextBlock Text="服务器IP: "   /></Border><Border HorizontalAlignment="Right" ><TextBox Text="192.168.2.223" x:Name="txb_ServerAdderess" VerticalAlignment="Center"  TextAlignment="Center" FontSize="16" Width="145"/></Border></StackPanel><StackPanel VerticalAlignment="Center"   Orientation="Horizontal"  Grid.Row="1"><Border HorizontalAlignment="Left" ><TextBlock Text="端口号: "   /></Border><Border HorizontalAlignment="Right"><TextBox Text="8000" x:Name="txb_Prot" Width="100" TextAlignment="Center"/></Border></StackPanel><Border Grid.Row="2" Width="150" Height="30"><Button x:Name="btn_OpenConnent" Content="打开服务器"  Click="Button_OpenProtClick"/></Border></Grid></GroupBox><GroupBox Header="写数据给PLC" Width="250" Height="150"  FontSize="20" BorderBrush="#FF0ABEFF" BorderThickness="2"><Grid><Grid.ColumnDefinitions><ColumnDefinition/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><StackPanel VerticalAlignment="Center"   Orientation="Horizontal"  Grid.Row="0"><Border HorizontalAlignment="Left" ><TextBlock Text="开   头: "   Width="70"/></Border><Border HorizontalAlignment="Right" ><TextBox Text="SN" x:Name="txb_WriteSN" VerticalAlignment="Center"  TextAlignment="Center" FontSize="16" Width="145"/></Border></StackPanel><StackPanel VerticalAlignment="Center"   Orientation="Horizontal"  Grid.Row="1"><Border HorizontalAlignment="Left" ><TextBlock Text="序列号: "   Width="70"/></Border><Border HorizontalAlignment="Right"><TextBox Text="123456789" x:Name="txb_WriteNume" Width="145" TextAlignment="Center" FontSize="16"/></Border></StackPanel><Border Grid.Row="2" Width="150" Height="30"><Button x:Name="btn_WriteDevice" Content="写入"  Click="btn_WriteDevice_Click"/></Border></Grid></GroupBox></StackPanel></Grid>
</Page>

页面后台代码

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;namespace WpfApp4.Views
{/// <summary>/// SocketPage.xaml 的交互逻辑/// </summary>public partial class SocketPage : Page{public SocketPage(){InitializeComponent();}/// <summary>/// 打开/关闭连接/// </summary>bool isConnent = false;/// <summary>/// 服务器已创建/// </summary>bool isOpenConnent = false;/// <summary>/// 触发写入/// </summary>bool btn_Write = false;//第一步:调用socket()函数创建一个用于通信的套接字private Socket listenSocket;//字典集合:存储IP和Socket的集合private Dictionary<string, Socket> OnLineList = new Dictionary<string, Socket>();//编码格式Encoding econding = Encoding.Default;private void Button_OpenProtClick(object sender, EventArgs e){if (isConnent){MessageBox.Show("服务器已开启,请勿重复点击!");return;}if (!isOpenConnent){//第一步:调用socket()函数创建一个用于通信的套接字listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);isOpenConnent = true;}//第二步:给已经创建的套接字绑定一个端口号,这一般通过设置网络套接口地址和调用Bind()函数来实现IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(this.txb_ServerAdderess.Text.Trim()), int.Parse(this.txb_Prot.Text.Trim()));try{listenSocket.Bind(endPoint);}catch (Exception ex){MessageBox.Show("服务器开启失败:" + ex.Message, "开启服务器");//listenSocket.Shutdown(SocketShutdown.Both);//listenSocket.Close();//MessageBox.Show("关闭服务器中......");isOpenConnent = false;return;}//第三步:调用listen()函数使套接字成为一个监听套接字listenSocket.Listen(10);//ShowMessage("服务器开启成功");MessageBox.Show("服务器开启成功");isConnent = true;this.Dispatcher.Invoke(new Action(() =>{txtb_serverData.Text = "服务器开启成功!等待客户端连接中......";btn_OpenConnent.Background = new SolidColorBrush(Colors.Green);}));if (isOpenConnent){//开启一个线程监听Task.Run(new Action(() =>{ListenConnection();}));}}private void ListenConnection(){try{while (true){Socket clientSocket = listenSocket.Accept();string ip = clientSocket.RemoteEndPoint.ToString();//MessageBox.Show(ip + "上线了");this.Dispatcher.Invoke(new Action(() =>{txtb_ConnentDevice.Text = "当前连接设备:" + ip;}));Task.Run(() => ReceiveMsg(clientSocket));Task.Run(() => WriteDeviceMsg(clientSocket));}}catch (Exception){throw;}}/// <summary>/// 接收方法/// </summary>/// <param name="clientSocket"></param>private void ReceiveMsg(Socket clientSocket){try{//    // 接收数据byte[] bytesToUse = new byte[60];int numberOfBytesRec = clientSocket.Receive(bytesToUse);string returndata = Encoding.ASCII.GetString(bytesToUse, 0, numberOfBytesRec);//Console.WriteLine("从客户端收到: " + returndata);this.Dispatcher.Invoke(new Action(() =>{txtb_serverData.Text = "从客户端收到: " + returndata;}));while (true){numberOfBytesRec = clientSocket.Receive(bytesToUse);returndata = Encoding.ASCII.GetString(bytesToUse, 0, numberOfBytesRec);Thread.Sleep(10);this.Dispatcher.Invoke(new Action(() =>{txtb_reData.Text = returndata;txtb_serverData.Text = "从客户端收到: " + returndata;}));//Console.WriteLine("从客户端收到: " + returndata);Thread.Sleep(1000);}}catch (Exception ex){MessageBox.Show("接收报错:" + ex.Message);}}private void WriteDeviceMsg(Socket clientSocket){// 发送数据回客户端string response = "Hello from server";byte[] msg = Encoding.ASCII.GetBytes(response);try{while (true){this.Dispatcher.Invoke(new Action(() =>{response = txb_WriteSN.Text.ToString() + txb_WriteNume.Text.ToString();msg = Encoding.ASCII.GetBytes(response);}));if (btn_Write){clientSocket.Send(msg);//Console.WriteLine("发送到客户端: " + response);btn_Write = false;}Thread.Sleep(1000);}}catch (Exception){throw;}}/// <summary>/// 消息发送/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_WriteDevice_Click(object sender, EventArgs e){btn_Write = true;return;}}
}

注意:要把当前连接PLC的网卡设置成服务器IP

最后启动测试就可以了;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/88598.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/88598.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ubuntu20.04基于tensorRT和c++跑yolo11

设备 系统&#xff1a;Ubuntu 20.04 显卡&#xff1a;NVIDIA GeForce RTX 3050 显卡驱动&#xff1a; Driver Version: 535.183.01 CUDA Version: 12.2 关键软件版本总结 Cmake: 3.28.6 Cuda&#xff1a; 12.2.2 Cudnn: 8.9.7 TensorRT: 10.8.0.43 Python&#xff1a;3.10.1…

玖玖NFT数字藏品源码(源码下载)

玖玖NFT数字藏品源码 这套还是很不错的&#xff0c;前端uniapp&#xff0c;后端FastAdmin&#xff0c;对接汇元支付&#xff0c;富友支付&#xff0c;对接avata链&#xff0c;感兴趣的自行下载研究 源码下载&#xff1a;https://download.csdn.net/download/m0_66047725/9133…

【Redis-05】高可用方案-主从哨兵

1 概述 高可用&#xff08;High Availability&#xff09;指系统在部分节点故障时仍能持续提供服务的能力。Redis 作为核心缓存组件&#xff0c;主流的高可用方案有主从复制、哨兵模式、集群模式三种。本文介绍主从复制、哨兵模式两种高可用方案。 2 主从复制 通过 “一主多从”…

焊接机器人智能节气装置

工业焊接作为现代制造业的重要组成部分&#xff0c;广泛应用于汽车、航空航天、建筑、船舶等多个领域。随着自动化技术的快速发展&#xff0c;焊接机器人已成为提升焊接效率和质量的关键装备。在传统焊接及部分自动化焊接过程中&#xff0c;气体流失问题仍然普遍存在&#xff0…

【6.1.0 漫画数据库技术选型】

漫画数据库技术选型 &#x1f3af; 学习目标&#xff1a;掌握架构师核心技能——数据库技术选型&#xff0c;针对不同业务场景选择最合适的数据库方案 &#x1f3db;️ 第一章&#xff1a;关系型数据库对比选型 &#x1f914; MySQL vs PostgreSQL vs TiDB 想象数据库就像不同…

CVE-2022-4262/CVE-2022-3038

CVE-2022-4262&#xff08;Linux内核UAF漏洞&#xff09;漏洞原理CVE-2022-4262是Linux内核中RDS&#xff08;Reliable Datagram Sockets&#xff09;协议实现的一个UAF&#xff08;Use-After-Free&#xff0c;释放后使用&#xff09;漏洞。具体来说&#xff1a;在rds_rdma_ext…

[Token]Token merging for Vision Generation

Token Compression for Vision Domain_Generation 文章目录Image GenerationToken Merging for Fast Stable Diffusion, CVPRW 2023.Token Fusion: Bridging the Gap between Token Pruning and Token Merging, WACV 2024ToDo: Token Downsampling for Efficient Generation of…

React封装过哪些组件-下拉选择器和弹窗表单

背景&#xff08;S - Situation&#xff09;&#xff1a;在某活动管理系统中&#xff0c;前端页面需要支持用户选择“要配置的当前活动”&#xff0c;并提供「新增」「编辑」功能&#xff0c;操作内容包括填写活动名称、ID、版本号等字段。原始实现逻辑分散、复用性差&#xff…

多租户架构下的多线程处理实践指南

在现代 SaaS 系统中&#xff0c;多租户架构&#xff08;Multi-Tenant Architecture&#xff09;已成为主流。然而&#xff0c;随着系统性能要求的提升和业务复杂度的增加&#xff0c;多线程成为不可避免的技术手段。但在多租户环境下使用多线程&#xff0c;容易引发数据错乱、租…

MyBatis插件机制揭秘:从拦截器开发到分页插件实战

一、拦截器体系架构解析 1.1 责任链模式在MyBatis中的实现 MyBatis通过动态代理技术构建拦截器链&#xff0c;每个插件相当于一个切面&#xff1a; // 拦截器链构建过程 public class InterceptorChain {private final List<Interceptor> interceptors new ArrayList<…

百度文心一言开源ERNIE-4.5深度测评报告:技术架构解读与性能对比

目录一、技术架构解读1.1、ERNIE 4.5 系列模型概览1.2、模型架构解读1.2.1、异构MoE&#xff08;Heterogeneous MoE&#xff09;1.2.2、视觉编码器&#xff08;Vision Encoder&#xff09;1.2.3、适配器&#xff08;Adapter&#xff09;1.2.4、多模态位置嵌入&#xff08;Multi…

Matplotlib 模块入门

Python 中有个非常实用的可视化库 ——Matplotlib。数据可视化是数据分析中不可或缺的环节&#xff0c;而 Matplotlib 作为 Python 的 2D 绘图库&#xff0c;能帮助我们生成高质量的图表&#xff0c;让数据更直观、更有说服力。接下来&#xff0c;我们将从 Matplotlib 的概述、…

LeetCode 3169.无需开会的工作日:排序+一次遍历——不需要正难则反,因为正着根本不难

【LetMeFly】3169.无需开会的工作日&#xff1a;排序一次遍历——不需要正难则反&#xff0c;因为正着根本不难 力扣题目链接&#xff1a;https://leetcode.cn/problems/count-days-without-meetings/ 给你一个正整数 days&#xff0c;表示员工可工作的总天数&#xff08;从第…

VUE3 el-table 主子表 显示

在Vue 3中&#xff0c;实现主子表&#xff08;主从表&#xff09;的显示通常涉及到两个组件&#xff1a;一个是主表&#xff08;Master Table&#xff09;&#xff0c;另一个是子表&#xff08;Detail Table&#xff09;。我们可以使用el-table组件来实现这一功能。这里&#x…

张量数值计算

一.前言前面我们介绍了一下pytorch还有张量的创建&#xff0c;而本章节我们就来介绍一下张量的计算&#xff0c;类型转换以及操作&#xff0c;这个是十分重要的&#xff0c;我们的学习目标是&#xff1a;掌握张量基本运算、掌握阿达玛积、点积运算 掌握PyTorch指定运算设备。Py…

部署项目频繁掉线-----Java 进程在云服务器内存不足被 OOM Killer 频繁杀死-----如何解决?

一、查询系统日志grep -i "java" /var/log/messages执行这条命令&#xff0c;检查系统日志里是否有 Java 进程被 OOM Killer 杀死的记录。日志中反复出现以下内容&#xff1a;Out of memory: Killed process 3679325 (java) total-vm:2947000kB, anon-rss:406604kB..…

【保姆级教程】基于anji-plus-captcha实现行为验证码(滑动拼图+点选文字),前后端完整代码奉上!

前言 验证码作为Web应用的第一道安全防线&#xff0c;其重要性不言而喻。但你是否还在为以下问题烦恼&#xff1a; 传统字符验证码用户体验差&#xff0c;识别率低&#xff1f;验证码安全性不足&#xff0c;轻易被爬虫破解&#xff1f;前后端对接繁琐&#xff0c;集成效率低&…

HTML-八股

1、DOM和BOM DOM是表示HTML或者XML文档的标准的对象模型&#xff0c;将文档中每个组件&#xff08;元素、属性等&#xff09;都作为一个对象&#xff0c;使用JS来操作这个对象&#xff0c;从而动态改变页面内容&#xff0c;结合等。 DOM是以树型结构组织文档内容&#xff0c;树…

ADI的EV-21569-SOM核心板和主板转接卡的链接说明

ADI提供给客户很多DSP的核心板&#xff0c;比如EV-21569-SOM&#xff0c;EV-21593-SOM&#xff0c;EV-SC594-SOM等&#xff0c;非常多&#xff0c;但是没有底板&#xff0c;光一个核心板怎么用呢&#xff1f;于是我就在想&#xff0c;我的21569评估板就有通用底板&#xff0c;能…

基于 Redisson 实现分布式系统下的接口限流

在高并发场景下&#xff0c;接口限流是保障系统稳定性的重要手段。常见的限流算法有漏桶算法、令牌桶算法等&#xff0c;而单机模式的限流方案在分布式集群环境下往往失效。本文将介绍如何利用 Redisson 结合 Redis 实现分布式环境下的接口限流&#xff0c;确保集群中所有节点的…