客户端服务器通信

编程入门 行业动态 更新时间:2024-10-28 20:20:59
本文介绍了客户端服务器通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使客户端异步接收来自服务器的命令? 服务器正在监视多个客户端, 客户端代码:仅当在客户端中单击按钮时此方法有效,但我希望此方法自动起作用.我应该将此代码放在客户端的什么地方?

how to make the client to receive commands from a server asynchronously? server is monitoring several clients, client side code: this works only when a button is clicked in client but i want this to work automatically. where should i put this code in client side?

private void button1_Click(object sender, EventArgs e) { try { byte[] buffer = new byte[1024]; int iRx = m_socClient.Receive(buffer); char[] chars = new char[iRx]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(buffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); txtDataRx.Text = szData; if (szData == "info") { string[] lines1 = System.IO.File.ReadAllLines(@"D:\test55.txt"); // string replyMsg = "client Reply: INFO command " ; // Convert the reply to byte array foreach (string line in lines1) { byte[] byData = System.Text.Encoding.ASCII.GetBytes(line); Socket workerSocket = (Socket)m_socClient; workerSocket.Send(byData); } } if (szData == "stop") { string replyMsg = "client Reply: STOP command "; // Convert the reply to byte array byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg); Socket workerSocket = (Socket)m_socClient; workerSocket.Send(byData); } /* if (szData == "file") { string replyMsg = "client Reply: FILE command "; // Convert the reply to byte array byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg); Socket workerSocket = (Socket)m_socClient; workerSocket.Send(byData); } */ } catch (SocketException se) { MessageBox.Show(se.Message); } }

问候, Amith

Regards, Amith

推荐答案

如果要异步执行某项操作,可以将其放入自己的线程中: If you want to do something asynchronously, you can put it into an own thread: Thread myThread = new Thread(ListeningToServer); myThread.IsBackground = true; myThread.Start(); ... private void ListeningToServer() { while (true) { //Put your code here } }

更多推荐

客户端服务器通信

本文发布于:2023-08-07 03:29:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1316706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   通信   服务器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!