本文介绍了客户端服务器通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使客户端异步接收来自服务器的命令? 服务器正在监视多个客户端, 客户端代码:仅当在客户端中单击按钮时此方法有效,但我希望此方法自动起作用.我应该将此代码放在客户端的什么地方?
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 } }
更多推荐
客户端服务器通信
发布评论