带有 .NET 客户端的 socat TCP 侦听器

socat TCP listener with .NET Client

我在 Linux (SLES 12) 上有一个 socat TCP 侦听器 运行ning。任何连接的客户端都会将一个字符串传递给套接字,socat 将执行一个脚本,该脚本根据该字符串进行一些处理。该脚本回显一些输出,这些输出被传递回客户端。

socat  TCP-LISTEN:9996,fork EXEC:/home/abhishek/hello.sh

下面是 hello.sh 脚本。

#!/bin/bash
read str
echo "[Hello] $str" | tee -a test.txt

当我 运行 ncat 客户端按预期工作时。 ncat能够取回数据并输出。

echo abhishek | ncat 192.168.1.12 9996
[Hello] abhishek

现在我想通过用 C# 编写的 .NET 客户端连接到 socat。下面是我想出的基于原始套接字的代码。

IPAddress address = IPAddress.Parse("192.168.1.12");
IPEndPoint ipe = new IPEndPoint(address, 9996);

Socket client = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

client.Connect(ipe);


byte[] msg = Encoding.ASCII.GetBytes("abhishek");

// Send the data through the socket.  
int bytesSent = client.Send(msg);
Console.WriteLine("Sent {0} bytes.", bytesSent);

byte[] bytes = new byte[128];
int bytesRec = client.Receive(bytes); ;
Console.WriteLine("Response text = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));

client.Shutdown(SocketShutdown.Both);
client.Close();

我收到 "Sent 8 bytes" 行,但之后客户端挂起接收。 hello.sh 收到客户端数据,因为 test.txt 包含新条目。当我终止客户端 (Ctrl+C) 时,socat 打印

2018/02/03 10:12:03 socat[21656] E write(4, 0xe530f0, 17): Broken pipe

我应该如何在 C# 中读取来自 socat 的回复?

谢谢

我能够使用 TcpClient 与 socat 建立通信并从脚本中获取输出。下面是我实现的代码的主要部分。

TcpClient client = new TcpClient("192.168.1.12", 9999);
NetworkStream stream = client.GetStream();

StreamWriter writer = new StreamWriter(stream) { AutoFlush = true };
StreamReader reader = new StreamReader(stream);

//Send message to socat.
writer.WriteLine(message);

//Receive reply from socat.
string reply = reader.ReadLine();

stream.close();
client.close();