在WinService中使用Socket数据交互

WinService服务教程:

https://www.cnblogs.com/cncc/p/7170951.html

Scoket代码:

在WinService中使用Socket数据交互

 

在WinService中使用Socket数据交互

在WinService中使用Socket数据交互


在WinService中使用Socket数据交互
  1 //服务地址
  2 public static string ipAddress = ConfigurationManager.AppSettings["ipAddress"].ToString();
  3 //服务端口
  4 public static string port = ConfigurationManager.AppSettings["port"].ToString();
  5 
  6 Thread threadWatch = null;// 负责监听客户端的线程
  7 Socket socketWatch = null;// 负责监听客户端的套接字
  8 Socket clientConnection = null;// 负责和客户端通信的套接字
  9 //服务启动
 10 protected override void OnStart(string[] args) {
 11 using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true)) {
 12 sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 开启服务");
 13 }
 14 
 15 // 定义一个套接字用于监听客户端发来的消息,包含三个参数(ipv4寻址协议,流式连接,tcp协议)
 16 socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 17 // 服务端发送消息需要一个ip地址和端口号
 18 IPAddress ip = IPAddress.Parse(ipAddress);
 19 // 把ip地址和端口号绑定在网路节点endport上
 20 IPEndPoint endPort = new IPEndPoint(ip, int.Parse(port));
 21 
 22 // 监听绑定的网路节点
 23 socketWatch.Bind(endPort);
 24 // 将套接字的监听队列长度设置限制为0,0表示无限
 25 socketWatch.Listen(0);
 26 // 创建一个监听线程
 27 threadWatch = new Thread(WatchConnecting);
 28 threadWatch.IsBackground = true;
 29 threadWatch.Start();
 30 }
 31 
 32 /// <summary>
 33 /// 监听客户端发来的请求
 34 /// </summary>
 35 private void WatchConnecting() {
 36 //持续不断监听客户端发来的请求
 37 while (true) {
 38 clientConnection = socketWatch.Accept();
 39 // 创建一个通信线程
 40 ParameterizedThreadStart pts = new ParameterizedThreadStart(acceptMsg);
 41 Thread thr = new Thread(pts);
 42 thr.IsBackground = true;
 43 thr.Start(clientConnection);
 44 }
 45 }
 46 /// <summary>
 47 /// 接收客户端发来的消息
 48 /// </summary>
 49 /// <param name="socket">客户端套接字对象</param>
 50 private void acceptMsg(object socket) {
 51 Socket socketServer = socket as Socket;
 52 try {
 53 while (true) {
 54 //创建一个内存缓冲区 其大小为10240字节 即10M
 55 byte[] recMsg = new byte[10240];
 56 //数据格式
 57 //��[{"TestTime":"2020-09-17 15:19:58","MachineNO":"1","SchoolNO":"80","StuNO":"12319623","TestResult":"172.4","ItemNO":1},{"TestTime":"2020-09-17 15:19:58","MachineNO":"1","SchoolNO":"80","StuNO":"12319623","TestResult":"71.9","ItemNO":2}]
 58 //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
 59 int count = socketServer.Receive(recMsg, recMsg.Length, 0);//接受数据
 60 Thread.Sleep(500);
 61 while (socketServer.Available > 0) {//参数 数据缓存区 起始位置 数据长度 值的按位组合
 62 int index = socketServer.Receive(recMsg, count, socketServer.ReceiveBufferSize, SocketFlags.None);
 63 count += index;
 64 Thread.Sleep(500);
 65 }
 66 if (count > 0) {
 67 //将机器接受到的字节数组转换为人可以读懂的字符串
 68 string dy = Encoding.UTF8.GetString(recMsg, 0, count);
 69 using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true)) {
 70 sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "已接收字符串:" + dy);
 71 }
 72 //切割数据 重新组合
 73 string getData = dy.Split('[')[1].Split(']')[0];
 74 using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true)) {
 75 sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "已转换字符串:" + getData);
 76 }
 77 //包装数据 以便反序列化
 78 getData = "[" + getData + "]";
 79 //获取数据列表
 80 var list = JsonConvert.DeserializeObject<List<gm11>>(getData);
 81 var len = list.Count();
 82 if (len == 2) {
 83 //如果是身高体重
 84 if (list[0].ItemNO == "1") {
 85 //首先添加体重
 86 string wname = list[1].StuNO;
 87 double wgmValue = Convert.ToDouble(list[1].TestResult);
 88 DateTime wcheckTime = Convert.ToDateTime(list[1].TestTime);
 89 int witem = Convert.ToInt32(list[1].ItemNO);
 90 DataOperate dal = new DataOperate();
 91 //新增体重数据
 92 Thread addThread = new Thread(new ThreadStart(delegate {
 93 dal.GmValueOperate(wname, wgmValue, wcheckTime, witem);
 94 }));
 95 addThread.Start();
 96 //线程阻塞,完成数据库操作再回传数据
 97 addThread.Join();
 98 
 99 //再加身高
100 string hname = list[0].StuNO;
101 double hgmValue = Convert.ToDouble(list[0].TestResult);
102 DateTime hcheckTime = Convert.ToDateTime(list[0].TestTime);
103 int hitem = Convert.ToInt32(list[0].ItemNO);
104 Thread add1Thread = new Thread(new ThreadStart(delegate {
105 dal.GmValueOperate(hname, hgmValue, hcheckTime, hitem);
106 }));
107 add1Thread.Start();
108 //线程阻塞,完成数据库操作再回传数据
109 add1Thread.Join();
110 //回传数据 告诉客户端结果
111 byte[] buffer = { 0xCC, 0xCC, 0x05, 0x00, 0x12, 0x7B, 0x22, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x3A, 0x22, 0x74, 0x72, 0x75, 0x65, 0x22, 0x7D };
112 clientConnection.Send(buffer);
113 }
114 //普通循环
115 else {
116 //保存数据到数据库
117 SaveData(list);
118 }
119 } else {
120 SaveData(list);
121 }
122 } else {
123 if (socketServer != null) {
124 socketServer.Shutdown(SocketShutdown.Both);
125 socketServer.Close();
126 }
127 }
128 }
129 } catch (Exception e) {
130 using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true)) {
131 sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "接收数据" + e.Message);
132 }
133 }
134 }
View Code

 

 

上一篇:Yarn资源调度过程详细(TEZ)


下一篇:CSS 计数器详解