控制台应用程序不想读取标准输入

3

我正在编写一个应用程序来管理其他控制台应用程序(游戏服务器-jampded.exe)。

当它在控制台中运行时,它可以正常地写入数据并读取命令。

在我的应用程序中,我将标准I/O重定向到了StreamWriter和StreamReader。

Public out As StreamReader
Public input As StreamWriter

Dim p As New Process()
p.StartInfo.FileName = My.Application.Info.DirectoryPath & "\" &
                       TextBox6.Text 'PATH TO JAMPDED.EXE
p.StartInfo.Arguments = TextBox1.Text 'EXTRA PARAMETERS
p.StartInfo.CreateNoWindow = True 
p.StartInfo.RedirectStandardInput = True
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.UseShellExecute = False
p.Start()

input = p.StandardInput
out = p.StandardOutput

Dim thr As Thread = New Thread(AddressOf updatetextbox)
thr.IsBackground = True
thr.Start()

Sub updatetextbox()
  While True
    While Not out.EndOfStream
      RichTextBox1.AppendText(out.ReadLine())
      RichTextBox1.AppendText(vbNewLine)
    End While
  End While
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) _
                                                       Handles Button2.Click
  input.WriteLine(TextBox4.Text)
  TextBox4.Text = ""
  input.Flush()
End Sub

当我按下“Button2”时,应该从我的文本框中写入STD/I文本,但“jampded.exe”似乎没有被写入。此外,在启动后输出正常工作,但在缓冲区有大量数据时很少添加新行。
我是做错了什么还是应用程序的问题?
1个回答

2

对于标准输入问题:

您确定启动的应用程序正在从标准输入读取数据(而不是捕获键盘事件或其他内容)吗?为了测试这一点,请将您想要发送到应用程序中的文本放在一个文本文件中(例如命名为commands.txt)。然后通过命令提示符将其发送到应用程序中,如下所示:

type commands.txt | jampded.exe

如果该应用程序读取这些命令,则确实从标准输入读取。如果没有,那么重定向标准输入并不能帮助您将数据发送到该应用程序。

对于标准输出问题:

与其启动自己的线程来处理来自其他应用程序的数据,我建议您尝试像这样做:

AddHandler p.OutputDataReceived, AddressOf OutputData
p.Start()
p.BeginOutputReadLine()

Private Sub AddLineToTextBox(ByVal line As String)
    RichTextBox1.AppendText(e.Data)
    RichTextBox1.AppendText(vbNewLine)
End Sub
Private Delegate Sub AddLineDelegate(ByVal line As String)

Private Sub OutputData(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
    If IsNothing(e.Data) Then Exit Sub
    Dim d As AddLineDelegate
    d = AddressOf AddLineToTextBox
    Invoke(d, e.Data)
End Sub
< p >需要调用 Invoke ,因为 OutputData 可能会在不同的线程上调用,而所有UI更新都必须在UI线程上发生。< / p> < p >在直接从StandardOutput流读取数据时,我曾经遇到了批量数据出现的相同问题。异步读取+事件处理程序组合解决了这个问题。< / p>

谢谢您的回复+1。虽然我已经找到了STD输入的解决方法,但即使使用您的代码,标准输出仍然有很大的延迟。 - Disa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接