// Asynchronous read call-back for the standard output and error streams of the executed process. // // This call-back method fills the state object's buffer with the received data, and writes it to the socket. private void LocalReadCallback(IAsyncResult iAsyncResult) { LocalStateObject localStateObject = (LocalStateObject)iAsyncResult.AsyncState; Socket socket = localStateObject.Socket; Stream stream = localStateObject.Stream; NVT nvt = new NVT(); try { int read = stream.EndRead(iAsyncResult); if (0 < read) { string str = Encoding.ASCII.GetString(localStateObject.Buffer, 0, read); // Debug. nvt.Write(localStateObject.Buffer, 0, read); int r = nvt.Read(localStateObject.Buffer, 0, read); // Lock the socket, just in case the other call-back wants to write at the same time. lock (socket) { socket.Send(localStateObject.Buffer, r, 0); } // Reassociate the stream's BeginRead() method with the LocalReadCallback(). stream.BeginRead(localStateObject.Buffer, 0, LocalStateObject.BUFFER_SIZE, new AsyncCallback(LocalReadCallback), localStateObject); } else { stream.Close(); } } catch (ObjectDisposedException) { // If we reach this point, it means that either the socket or the processed stream were closed, so we have nothing // else to do here. Close the socket, the process, and the stream, just in case. localStateObject.Socket.Close(); localStateObject.Process.Close(); localStateObject.Stream.Close(); } }
// Asynchronous read call-back for the socket object. // // This call-back method fills the state object's buffer with the received data, and writes it to the process' standard input. private void ReadCallback(IAsyncResult iAsyncResult) { StateObject stateObject = (StateObject)iAsyncResult.AsyncState; Socket socket = stateObject.Socket; NVT nvt = new NVT(); try { int read = socket.EndReceive(iAsyncResult); if (0 < read) { // Handle the received data and reassociate the call-back with the socket's BeginReceive(). StreamWriter streamWriter = stateObject.Process.StandardInput; string str = Encoding.ASCII.GetString(stateObject.Buffer, 0, read); // Debug. nvt.Write(stateObject.Buffer, 0, read); int r = nvt.Read(stateObject.Buffer, 0, read); streamWriter.Write(Encoding.ASCII.GetString(stateObject.Buffer, 0, r)); socket.BeginReceive(stateObject.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), stateObject); } else { socket.Close(); } } catch(ObjectDisposedException) { // If we reach this point, it means that either the socket or the process' standard input were closed, so we have nothing // else to do here. Close the socket and the process, just in case. stateObject.Socket.Close(); stateObject.Process.Close(); } }