c#tcp备忘及networkstream.length此流不支持查找解决

2/11/2016来源:C#应用人气:2677

服务端


  bool isRunning = true;
  MouseKeyBoard mk = new MouseKeyBoard();

void InitTcpServer(int port)
        {
            Thread t = new Thread(() =>
            {
                TcpListener listener = new TcpListener(ipAddress.Any, port);
                listener.Start();
                Log("监听:" + port);


                while (isRunning)
                {
                    var tcpClient = listener.AcceptTcpClient();
                    try
                    {
                        Thread t2 = new Thread(() =>
                        {
                            NetworkStream clientStream = tcpClient.GetStream();

                            

                            while (isRunning)
                            {
                                try
                                {
                                    if (!clientStream.DataAvailable)
                                    {
                                        Thread.Sleep(100); //否则死循环,cpu占用超高
                                        continue;
                                    }
                                    byte[] buffer = new byte[tcpClient.Available]; //new byte[clientStream.Length]; //报错此流不支持查找
                                    int readBytes = 0;
                                    readBytes = clientStream.Read(buffer, 0, buffer.Length); 
                                    clientStream.Flush();
                                    
                                    string request = Encoding.UTF8.GetString(buffer).Trim();
                                    Log(request);


                                    if (request.StartsWith("SetTime|"))
                                    {
                                        var str = DateTime.Parse(request.Substring(8)).ToString("yyyyMMdd") + DateTime.Now.ToString("HHmmss");
                                        SetLocalTimeByStr(str);
                                        clientStream.Flush();
                                        clientStream.Write(Encoding.Default.GetBytes("ok"), 0, 2); //发送给客户端
                                        clientStream.Flush();
                                    }
                                    else if (request.StartsWith("MouseClick|"))
                                    {
                                        var arr = request.Split('|');
                                        if (arr.Length >= 2)
                                        {
                                            mk.MouseClick(arr[1]);
                                        }
                                    }
                                    else if (request.StartsWith("ShutDown|"))
                                    {
                                        ExecuteCmd("shutdown -s -t 120");
                                    }
                                    else if (request.StartsWith("CancelShutDown|"))
                                    {
                                        ExecuteCmd("shutdown -a");
                                    }else if (request.StartsWith("SendString"))
                                    {
                                        var arr = request.Split('|');
                                        if (arr.Length >= 2)
                                        {
                                            string str = arr[1];
                                            this.button1.BeginInvoke(new Action(() => {
                                                mk.SendKeys(str);
                                            }));
                                            
                                        }
                                    }


                                }
                                catch (Exception ex)
                                {
                                    Log("ex|" + ex.Message + ex.StackTrace);
                                }

                                Thread.Sleep(100);
                            }
                        });
                        t2.Start();
                    }
                    catch (Exception ex2)
                    {
                        Log("ex2|" + ex2.Message + ex2.StackTrace);
                    }

                    Thread.Sleep(100);
                }


            });

            t.Start();
        }

 

客户端


TcpClient tcpClient = new TcpClient();
bool isRunning = true;


PRivate
void button2_Click(object sender, EventArgs e) { tcpClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.0.168"), Convert.ToInt32(this.textBox2.Text.Trim()))); MessageBox.Show("连接成功."); } private void button1_Click(object sender, EventArgs e) { Thread t = new Thread(() => { NetworkStream clientStream = tcpClient.GetStream(); string request = "SetTime|" + this.textBox1.Text.Trim(); byte[] requestBuffer = Encoding.Default.GetBytes(request); clientStream.Write(requestBuffer, 0, requestBuffer.Length); clientStream.Flush(); var buffer = new byte[1024]; while (isRunning) { clientStream.Read(buffer, 0, buffer.Length); string str = Encoding.Default.GetString(buffer).Trim(); if (str.StartsWith("ok")) { Invoke(() => { MessageBox.Show("修改时间成功."); }); } Thread.Sleep(100); } }); t.Start(); this.button1.Enabled = false; }

 

From:http://www.cnblogs.com/xuejianxiyang/p/5085077.html