C # tcp memo and networkstream. length this stream cannot be searched and resolved,
Server
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 ("listener:" + 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); // otherwise, the cpu usage is ultra-high. continue;} byte [] buffer = new byte [tcpClient. available]; // new byte [clientStream. length]; // the error message returned. This stream does not support 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); // send it to the client 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 ();}
Client
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 ("connection successful. ");} private void button#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 ("modification time successful. ") ;}) ;}thread. sleep (100) ;}}); t. start (); this. button1.Enabled = false ;}