所以我正在创建一个程序,可以从Windows命令提示符下读取输出。它的工作原理如下:
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
在事件处理程序中,我将输出联网。 (服务器也使用流以C#编写)
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data))
{
socketInput.WriteLine(e.Data);
socketInput.Flush();
}
}
这几乎可以正常工作,除了一些特殊字符(如瑞典字符)在服务器端打印为乱码。我仅在客户端尝试过Console.WriteLine(e.Data)
,而且似乎可以正常工作,因此我认为这与我在网络部分的编码有关。有人可以在这里向我解释问题吗?我试图找出要使用的编码,但没有任何运气。
顺便说一句。这是套接字流(它们在服务器端类似)
socketInput = new StreamWriter(client.GetStream());
socketOutput = new StreamReader(client.GetStream());
套接字初始化客户端:
TcpClient client = new TcpClient();
//retry connection until found
while (true)
{
try
{
client.Connect("127.0.0.1", 4444);
}
catch (Exception ex)
{
//handle errors
continue;
}
if (client.Connected) break;
System.Threading.Thread.Sleep(1);
}
套接字初始化服务器端:
TcpListener listener = new TcpListener(IPAddress.Any, 4444);
listener.Start();
Console.WriteLine("Waiting for a connection...");
TcpClient client = listener.AcceptTcpClient();
接收代码(在单独的线程中运行):
while(true)
{
try
{
Console.WriteLine(socketOutput.ReadLine());
} catch(Exception e)
{
Console.WriteLine("Connection lost!");
return;
}
}