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
英文地址,請注明出處:http://en.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;確保集群中所有節點的…