123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.Windows.Forms;
- using UAS_MES_NEW.DataOperate;
- using UAS_MES_NEW.Entity;
- namespace UAS_MES_NEW.PublicMethod
- {
- class GetDataFromDevice
- {
- DataHelper dh = SystemInf.dh;
- public GetDataFromDevice()
- {
- }
- private bool isOpen = false;
- Thread threadWatch = null; //负责监听客户端的线程
- Socket socketWatch = null; //负责监听客户端的套接字
- Socket socConnection;
- public bool IsOpen
- {
- get
- {
- return isOpen;
- }
- set
- {
- isOpen = value;
- }
- }
- public string IP
- {
- get
- {
- return iP;
- }
- set
- {
- iP = value;
- }
- }
- public string Port
- {
- get
- {
- return port;
- }
- set
- {
- port = value;
- }
- }
- private string iP;
- private string port;
- public bool Open()
- {
- try
- {
- //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)
- socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //服务端发送信息 需要1个IP地址和端口号
- IPAddress ipaddress = IPAddress.Parse(iP);
- //将IP地址和端口号绑定到网络节点endpoint上
- IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(port));
- //监听绑定的网络节点
- socketWatch.Bind(endpoint);
- //将套接字的监听队列长度限制为20
- socketWatch.Listen(20);
- //创建一个监听线程
- threadWatch = new Thread(WatchConnecting);
- //将窗体线程设置为与后台同步
- threadWatch.IsBackground = true;
- //启动线程
- threadWatch.Start();
- isOpen = true;
- return true;
- }
- catch (Exception e)
- {
- MessageBox.Show(e.Message);
- return false;
- }
- }
- private void WatchConnecting()
- {
- socConnection = socketWatch.Accept();
- while (true) //持续不断监听客户端发来的请求
- {
- byte[] data = new byte[1024];
- socConnection.Receive(data);
- //获取发送客户端的IP地址
- string clientIP = socConnection.RemoteEndPoint.ToString();
- int length = data[5];
- byte[] datashow = new byte[length + 6];
- for (int i = 0; i <= length + 5; i++)
- {
- datashow[i] = data[i];
- }
- string stringdata = BitConverter.ToString(datashow);//把数组转换成16进制字符串
- }
- }
- public void Close()
- {
- threadWatch.Abort();
- socketWatch.Close();
- isOpen = false;
- }
- public void SendOrder(string Code)
- {
- //socConnection.Send(null);
- }
- }
- }
|