private void Receive_Event(object sender, EventArgs e) { CReceive cReceive = (CReceive)sender; string[] ls = cReceive.ReceiveString.Split('|'); if (ls.Length > 0) { if (ls[0] == "0") { // ls[0]请求 ls[1] 机台编号 ls[2] 配方Id ls[3] 请求量 ls[4] 缸号 DistributionRequest(ls[1], ls[2], ls[3], ls[4], cReceive.RemoteIP); } else if (ls[0] == "1") { //终止 // ls[0]请求 ls[1] 机缸编号 lock (Golbal.MyQueueList) { try { Golbal.MyQueueList.RemoveAll(s => s.DeviceCode == ls[1]); tcpclass.SendString(cReceive.RemoteIP, "终止成功!"); } catch { tcpclass.SendString(cReceive.RemoteIP, "终止失败!"); } } } else if (ls[0] == "2") { // ls[0]请求 ls[1] 机台编号 ls[2] 机缸编号 ls[3] 皂洗剂 ls[4] 水 WashingRequest(ls[1], ls[2], ls[3], ls[4], cReceive.RemoteIP); } else if (ls[0] == "3") { try { if (Golbal.CurrentWashingaModel != null && Golbal.WashingWaterStep > 0) { if (Golbal.CurrentWashingaModel.DeviceCode == ls[1]) { //停止配送 WashingFormulaEnd(null, null); } } else { Golbal.MyWashingList.RemoveAll(s => s.DeviceCode == ls[1]); } tcpclass.SendString(cReceive.RemoteIP, "终止成功!"); } catch { tcpclass.SendString(cReceive.RemoteIP, "终止失败!"); } } } }
//监听端口 private void ListenClient() { byte[] buffer = null; IPAddress localIP = GetIPAddress(); TcpListener listener = new TcpListener(localIP, localPort); //用本地IP和端口实例化Listener listener.Start(); //开始监听 try { Task.Factory.StartNew(() => //线程执行任务 { while (true) { CReceive creceive = new CReceive(); client = listener.AcceptTcpClient();//接受一个Client buffer = new byte[client.ReceiveBufferSize]; creceive.RemoteIP = (client.Client.RemoteEndPoint as IPEndPoint).Address; stream = client.GetStream(); //获取网络流 stream.Read(buffer, 0, buffer.Length); //读取网络流中的数据 creceive.ReceiveString = Encoding.Default.GetString(buffer).Trim('\0'); //转换成字符串 stream.Close(); //关闭流 client.Close(); //关闭Client Receive_Event(creceive, null);//触发接收事件 Thread.Sleep(100); } }); } catch (Exception ex) { MessageBox.ShowTip(ex.ToString()); } }