一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

本文采用的是读取本地文件,因为没有相机,所以只能够这么操作,基本上类似。

作业中的代码如图:

配置中“作业属性”->“编辑脚本”->“C#脚本”。

作业脚本代码如下:

  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) == "start")
210           {
211             MyJob.RunContinuous();
212             //MessageBox.Show("接受到的数据:"+Encoding.ASCII.GetString(receiveBuffer,0,bytesReceived);
213           }
214           
215           if(Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived) == "stop")
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  
264 }

C# Form界面如下:

代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 using System.Net;
11 using System.Net.Sockets;
12 using System.Threading;
13  
14 namespace TCPClientApplicationProgram
15 {
16     public partial class Form1 : Form
17     {
18         Socket clientSocket;
19         Thread clientThread;
20  
21         public Form1()
22         {
23             InitializeComponent();
24  
25             //对跨线程的非法错误不检查
26             Control.CheckForIllegalCrossThreadCalls = false;
27  
28             this.IP_textBox1.Text = "127.0.0.1";
29  
30             this.Port_textBox2.Text = "6001";
31         }
32  
33         private void Send_button_Click(object sender, EventArgs e)
34         {
35             byte[] data = new byte[1024];
36  
37             //对输入信息进行编码并放到一个字节数组
38             data = Encoding.ASCII.GetBytes(this.Content_textBox3.Text);
39  
40             //向服务器发送信息
41             clientSocket.Send(data, data.Length, SocketFlags.None);
42         }
43  
44         private void ConnectSever_button1_Click(object sender, EventArgs e)
45         {
46             if(this.IP_textBox1.Text=="")
47             {
48                 MessageBox.Show("请输入IP!");
49                 return;
50             }
51  
52             //开启一个子线程,连接到服务器
53             clientThread = new Thread(new ThreadStart(ConnectToServer));
54             clientThread.Start();
55         }
56  
57         private void ConnectToServer()
58         {
59             byte[] data = new byte[1024];
60  
61             //网络地址和服务端口的组合称为端点,IPEndPoint类表示这个端口
62             IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(this.IP_textBox1.Text), int.Parse(this.Port_textBox2.Text));
63  
64             //初始化Socket
65             clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
66  
67             //将套接字与远程服务器地址相连
68             try
69             {
70                 //连接到服务器
71                 clientSocket.Connect(ipep);
72             }
73             catch(SocketException ex)
74             {
75                 MessageBox.Show("connect error:" + ex.Message);
76             }
77         }
78     }
79 }

运行效果:

posted on 2021-03-01 15:31  一杯清酒邀明月  阅读(2173)  评论(0编辑  收藏  举报