c# - Minimaslistic Telnet Library - Read output to the end -
i working on project should run commands on unix servers , full output of commands. purpose, using minimaslistic telnet library code project (http://www.codeproject.com/articles/19071/quick-tool-a-minimalistic-telnet-library). now, works fine excepting output, because want read all, not portion of it. can have commands may take long time. here read output method in minimaslistic telnet library :
public string read() { if (!tcpsocket.connected) return null; stringbuilder sb=new stringbuilder(); { parsetelnet(sb); system.threading.thread.sleep(timeoutms); } while (tcpsocket.available > 0); return sb.tostring(); } void parsetelnet(stringbuilder sb) { while (tcpsocket.available > 0) { int input = tcpsocket.getstream().readbyte(); switch (input) { case -1 : break; case (int)verbs.iac: // interpret command int inputverb = tcpsocket.getstream().readbyte(); if (inputverb == -1) break; switch (inputverb) { case (int)verbs.iac: //literal iac = 255 escaped, append char 255 string sb.append(inputverb); break; case (int)verbs.do: case (int)verbs.dont: case (int)verbs.will: case (int)verbs.wont: // reply commands "wont", unless sga (suppres go ahead) int inputoption = tcpsocket.getstream().readbyte(); if (inputoption == -1) break; tcpsocket.getstream().writebyte((byte)verbs.iac); if (inputoption == (int)options.sga ) tcpsocket.getstream().writebyte(inputverb == (int)verbs.do ? (byte)verbs.will:(byte)verbs.do); else tcpsocket.getstream().writebyte(inputverb == (int)verbs.do ? (byte)verbs.wont : (byte)verbs.dont); tcpsocket.getstream().writebyte((byte)inputoption); break; default: break; } break; default: sb.append( (char)input ); break; } } }
this code sample reads output, asynchronously, need wait output before quitting. there idea changing code meet requirements? thank you!
i agree joachim, calling read in loop , parsing end out output best approach. unfortunately me, output didn't have standardize ending each command executed. instead, used read timeout of stream approximate end of output (i realize isn't perfect). set higher initial timeout allow data start flowing, , lowered timeout find end of output. looks this:
static string readfromstream(int initialtimeout, int subsequenttimeout) { // initialize output string output = null; try { // set initial read timeout -- needed because // takes while before data starts flowing stream.readtimeout = initialtimeout; while (stream.canread) { // read bytes in stream readbuffer = new byte[tcpclient.receivebuffersize]; stream.read(readbuffer, 0, tcpclient.receivebuffersize); // convert bytes string , save output output = string.format("{0}{1}", output, encoding.ascii.getstring(readbuffer).trim()); // set subsequent read timeout stream.readtimeout = subsequenttimeout; } } // since don't know when output end, wait for, , catch timeout catch (ioexception) { } // return output return output; }
Comments
Post a Comment