简体   繁体   English

.NET客户端的socat TCP侦听器

[英]socat TCP listener with .NET Client

I have a socat TCP listener running on Linux (SLES 12). 我有一个在Linux(SLES 12)上运行的socat TCP侦听器。 Any client that connects will pass a string to the socket and socat will execute a script which does some work with based on the string. 任何连接的客户端都会将一个字符串传递给套接字,而socat将执行一个脚本,该脚本根据该字符串进行一些工作。 The script echos some output which is passed back to client. 该脚本回显一些输出,该输出将传递回客户端。

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

Below is the hello.sh script. 下面是hello.sh脚本。

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

When I run ncat client this works as expected. 当我运行ncat客户端时,它可以按预期工作。 ncat is able to get the data back and output it. ncat能够取回数据并将其输出。

echo abhishek | ncat 192.168.1.12 9996
[Hello] abhishek

Now I want to connect to socat through a .NET client written in C#. 现在,我想通过用C#编写的.NET客户端连接到socat。 Below is the raw socket based code I have come up with. 下面是我提出的基于原始套接字的代码。

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();

I get the line "Sent 8 bytes" but after that client hangs on Receive. 我得到“已发送8个字节”行,但是在该客户端挂起Receive之后。 The client data is received by hello.sh becaused test.txt contains new entry. 客户端数据由hello.sh接收,因为test.txt包含新条目。 When I kill the client (Ctrl+C) socat prints 当我杀死客户端(Ctrl + C)时,socat打印

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

How should I read the reply from socat in C#? 我应该如何阅读C#中socat的回复?

Thanks 谢谢

I was able to use TcpClient to establish communication with socat and get the output from script. 我能够使用TcpClient与socat建立通信并从脚本获取输出。 Below is the main part of code I implemented. 以下是我实现的代码的主要部分。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM