VisionPro C# 编写作业脚本实现TCP服务器的监听

上一节中已经在脚本中添加了代码,实际操作这篇内容,那需要完成上一篇的内容:编写二维码识别Quickbuild工程,本文在作业配置中添加代码,完整代码如下:

  1 using System;
  2 using System.Net;
  3 using System.Text;
  4 using System.Net.Sockets;
  5 using System.Threading;
  6 using System.Windows.Forms;
  7 using System.Collections.Generic;
  8 using Cognex.VisionPro;
  9 using Cognex.VisionPro.QuickBuild;
 10  
 11  
 12 public class UserScript : CogJobBaseScript
 13 {
 14   //集合可以看似数组,集合的长度是可变得,其元素是object类型
 15   //泛型集合时指定了数据类型的集合
 16   private object _lock=new object();
 17   
 18   //定义NetworkStream的泛型集合
 19   private List<NetworkStream>_streams = new List<NetworkStream>();
 20   
 21   //定义TCPClient的泛型集合
 22   private List<TcpClient>_clients = new List<TcpClient>();
 23   
 24   //服务器端监听对象
 25   private TcpListener _listener;
 26   
 27   //连接线程
 28   private Thread _connectionThread;
 29   
 30   //定义Thread泛型集合
 31   private List<Thread> _threads=new List<Thread>();
 32   
 33   //接受数据总长度
 34   private long _totalBytes;
 35   
 36   //作业
 37   private CogJob MyJob;
 38  
 39 #region "When an Acq Fifo Has Been Constructed and Assigned To The Job"
 40   // This function is called when a new fifo is assigned to the job.  This usually
 41   // occurs when the "Initialize Acquisition" button is pressed on the image source
 42   // control.  This function is where you would perform custom setup associated
 43   // with the fifo.
 44   public override void AcqFifoConstruction(Cognex.VisionPro.ICogAcqFifo fifo)
 45   {
 46   }
 47 #endregion
 48  
 49 #region "When an Acquisition is About To Be Started"
 50   // Called before an acquisition is started for manual and semi-automatic trigger
 51   // models.  If "Number of Software Acquisitions Pre-queued" is set to 1 in the
 52   // job configuration, then no acquisitions should be in progress when this
 53   // function is called.
 54   public override void PreAcquisition()
 55   {
 56     // To let the execution stop in this script when a debugger is attached, uncomment the following lines.
 57     // #if DEBUG
 58     // if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
 59     // #endif
 60  
 61   }
 62 #endregion
 63  
 64 #region "When an Acquisition Has Just Completed"
 65   // Called immediately after an acquisition has completed.
 66   // Return true if the image should be inspected.
 67   // Return false to skip the inspection and acquire another image.
 68   public override bool PostAcquisitionRefInfo(ref Cognex.VisionPro.ICogImage image,
 69                                                   Cognex.VisionPro.ICogAcqInfo info)
 70   {
 71     // To let the execution stop in this script when a debugger is attached, uncomment the following lines.
 72     // #if DEBUG
 73     // if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
 74     // #endif
 75  
 76     return true;
 77   }
 78 #endregion
 79  
 80 #region "When the Script is Initialized"
 81   //Perform any initialization required by your script here.
 82   public override void Initialize(CogJob jobParam)
 83   {
 84     //DO NOT REMOVE - Call the base class implementation first - DO NOT REMOVE
 85     base.Initialize(jobParam);
 86     
 87     //将当前作业可以复制给Myjob
 88     MyJob = jobParam;
 89     
 90     //开启线程
 91     StartThreading();
 92   }
 93 #endregion
 94   
 95   //开启线程实现服务器的端口监听
 96   private void StartThreading()
 97   {
 98     try 
 99     {
100       _totalBytes = 0;
101       
102       //_connectionThread对象实例化
103       _connectionThread = new System.Threading.Thread(new ThreadStart(ConnectToClient));
104       
105       //线程后台运行
106       _connectionThread.IsBackground = true;
107       
108       //线程开始运行
109       _connectionThread.Start();
110     }
111     catch(Exception ex)
112     {
113       MessageBox.Show("线程启动失败");
114     }
115   }
116   
117   //连接到客户端
118   private void ConnectToClient()
119   {
120     try
121     {
122       //开始监听6001端口
123       _listener = new TcpListener(IPAddress.Any, 6001);
124       
125       _listener.Start();
126     }
127     catch(SocketException se)
128     {
129       MessageBox.Show("服务器监听失败" + se.Message);
130       
131       StopServer();
132       
133       return;
134     }
135     
136     //监听客户端的连接请求
137     try
138     {
139       for(;;)
140       {
141         //等待客户端的连接请求
142         TcpClient client = _listener.AcceptTcpClient();
143         
144         //创建线程开始接受客户端数据
145         Thread t = new Thread(new ParameterizedThreadStart(ReceiveDataFromClient));
146         
147         //线程后台运行
148         t.IsBackground = true;
149         
150         //线程优先级
151         t.Priority = ThreadPriority.AboveNormal;
152         
153         //线程名称
154         t.Name = "Handle Client";
155         
156         //开启线程
157         t.Start(client);
158         
159         //将线程对象添加到泛型集合里
160         _threads.Add(t);
161         
162         //将客户端添加到泛型集合里
163         _clients.Add(client);
164       }
165     }
166     catch(SocketException ex)
167     {
168       MessageBox.Show("Socket错误" + ex.Message);
169     }
170     catch(Exception ex)
171     {
172       MessageBox.Show("异常错误" + ex.Message);
173     }
174   }
175   
176   //接受客户端传过来的数据
177   public void ReceiveDataFromClient(object clientObject)
178   {
179     //定义TcpClient对象并赋值
180     TcpClient client = clientObject as TcpClient;
181     
182     //定义NetworkStream对象并赋值
183     NetworkStream netStream = null;
184     
185     try
186     {
187       //获取客户端的网络数据流
188       netStream = client.GetStream();
189     }
190     catch(Exception ex)
191     {
192       if(netStream != null) netStream.Close();
193       MessageBox.Show("异常错误" + ex.Message);
194       return;
195     }
196     
197     if(netStream.CanRead)
198     {
199       //将数据流添加到_streams泛型集合里
200       _streams.Add(netStream);
201       try
202       {
203         byte[] receiveBuffer = new byte[512];
204         int bytesReceived;
205         
206         //循环读取客户端发来的数据
207         while((bytesReceived = netStream.Read(receiveBuffer, 0, receiveBuffer.Length)) > 0)
208         {
209           if(Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived) == "s")
210           {
211             MyJob.RunContinuous();
212             //MessageBox.Show("接受到的数据:"+Encoding.ASCII.GetString(receiveBuffer,0,bytesReceived);
213           }
214           
215           if(Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived) == "e")
216           {
217             MyJob.Stop();
218             //MessageBox.Show("接受到的数据:"+Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived));
219           }
220         }
221       }
222       catch(Exception ex)
223       {
224         MessageBox.Show("异常错误" + ex.Message);
225       }
226     }
227   }
228   
229   //停止服务器
230   private void StopServer()
231   {
232     if(_listener != null)
233     {
234       //关闭TCP监听
235       _listener.Stop();
236       
237       //等待服务器线程中断
238       _connectionThread.Join();
239       
240       //关闭所有客户端的网络数据流
241       foreach(NetworkStream s in _streams)
242         s.Close();
243       
244       //清除_streams泛型集合里的内容
245       _streams.Clear();
246       
247       //关闭客户端连接
248       foreach(TcpClient client in _clients)
249         client.Close();
250       
251       //清除_clients泛型集合里的内容
252       _clients.Clear();
253       
254       //等待所有客户端线程中断
255       foreach(Thread t in _threads)
256         t.Join();
257       
258       //清除_threads泛型集合里的内容
259       _threads.Clear();
260     
261     }
262   }
263 }

需要一个超级终端:HyperTrm,这个百度上能够下载,毕竟是购买的课程,虽然不贵,但是分享出来感觉有点不妥,所以还是不分享终端及如何连接喽。见谅。

效果:在超级终端界面输入"s"后弹出的效果如下:

原文地址:https://www.cnblogs.com/ybqjymy/p/14463878.html