0

我正在用 C# 编写一个简单的程序,它允许客户端连接到服务器并在该服务器上运行 MS DOS 命令。

该程序运行良好,后来我决定在客户端连接到服务器时运行 cmd.exe 进程,这就是我坚持的地方。我想要这个,以便我可以运行诸如CD之类的命令并更改工作目录,以前这没有效果,因为 cmd.exe 进程在命令运行后关闭。

如果进程退出,我似乎只能从StandardOutput和流中读取,有什么解决方法吗?StandardError

这是我在程序中使用的一些代码:

*创建并返回 cmd.exe 进程:*

private Process createDOS()
{
    try
    {
        // Create a ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo("cmd","");

        // Set up the values
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        startInfo.RedirectStandardInput = true;
        startInfo.CreateNoWindow = false;

        // Create a cmd.exe process
        Process process = new Process();

        // Apply the start info and run
        process.StartInfo = startInfo;

        process.Start();  

        return process;
    }
    catch (Exception)
    {
        return null;
    }
}

将响应格式化为字符串的方法:

private string findResponse(StreamReader err,StreamReader outp)
{
    string output = outp.ReadToEnd();
    string error = err.ReadToEnd();

    string ret = "";

    // Add the output to the return field if the process actually output data
    if (output.Length > 0)
    {
        ret = "OUTPUT : " + output;
    }

    // Then attempt to add data from the error stream
    if (error.Length > 0)
    {
        // If output was read, add a newline character separating the two fields
        if (ret.Length > 0) ret = ret + Environment.NewLine;
        ret = ret + "ERROR : " + error;
    }

    // If there's no output, that means there's no error, which means the execution was silently succesful
    if (ret.Length <= 0)
    {
        ret = "Command execution succesful!";
    }
    return ret;
}

服务器侦听器块:

private void run()
{
    while (true)
    {

        Stream stream = null;
        StreamReader sr = null;
        StreamWriter sw = null;
        Socket socket = null;
        Process proc = null;

        try
        {
            socket = server.AcceptSocket();

            stream = new NetworkStream(socket);

            sr = new StreamReader(stream);
            sw = new StreamWriter(stream);

            String mode = sr.ReadLine();

            sw.WriteLine("Serverside link connected");
            sw.Flush();

            // Create cmd process in WINPROCESS mode

            if (mode == "WINPROCESS")
            {
                proc = createDOS();
            }

            String line;
            while ((line = sr.ReadLine()) != null)
            {
                if (mode == "WINPROCESS")
                {
                    proc.StandardInput.WriteLine(line);
                    proc.StandardInput.Flush();

                    // Response
                    sw.WriteLine(findResponse(proc.StandardError, proc.StandardOutput));
                    sw.Flush();

                }
                else
                {
                    sw.WriteLine(exeDOS(line));
                    sw.Flush();
                }
            }

        }
        catch (Exception ex)
        {
            // Silence
        }
        finally
        {
            if (socket != null) socket.Close();
            if (stream != null) stream.Close();
            if (sw != null) sw.Close();
            if (sr != null) sr.Close();
            if (proc != null) proc.Close();
        }
    }
}

任何帮助将不胜感激,谢谢!

4

1 回答 1

0

您需要为OutputDataReceivedErrorDataReceived事件添加一个处理程序:

    process.StartInfo.RedirectStandardOutput = true;
    process.OutputDataReceived += 
        new DataReceivedEventHandler(process_OutputDataReceived);

    process.StartInfo.RedirectStandardError = true;
    process.ErrorDataReceived += 
        new DataReceivedEventHandler(process_ErrorDataReceived);

    if (process.Start())
    {
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();
        process.WaitForExit();
    }
}

void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine(e.Data);
}

void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine(e.Data);
}
于 2013-02-26T13:55:52.567 回答