Search code examples
c#socketssocat

socat TCP listener with .NET Client


I have a socat TCP listener running on Linux (SLES 12). 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. 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.

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

When I run ncat client this works as expected. ncat is able to get the data back and output it.

echo abhishek | ncat 192.168.1.12 9996
[Hello] abhishek

Now I want to connect to socat through a .NET client written in C#. 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. The client data is received by hello.sh becaused test.txt contains new entry. When I kill the client (Ctrl+C) socat prints

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#?

Thanks


Solution

  • I was able to use TcpClient to establish communication with socat and get the output from script. 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();