本文采用的是讀取本地文件,因為沒有相機,所以只能夠這么操作,基本上類似。
作業中的代碼如圖:
配置中“作業屬性”->“編輯腳本”->“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 }
運行效果: