Home > Enterprise >  How to keep a TCP connection open and perform multiple Writes/Reads in C# .NET?
How to keep a TCP connection open and perform multiple Writes/Reads in C# .NET?

Time:11-02

There are multiple posts that describe the performance benefit of keeping a TCP connection open, instead of closing and opening each time you need to read or write. For example:

Best practice: Keep TCP/IP connection open or close it after each transfer?

I'm communicating with an RPC based device that takes json commands. The example I have from the device vendor opens and closes a connection each time they send a command. This is what I currently do via TcpClient in a using statement, but I'd like to see if there's anyway I could improve upon what I've already done. In fact, I had attempted this when starting the project, but couldn't figure out how to do so, so closed each time out of frustration and necessity. My latest experiment using sockets because all posts indicate doing so as a necessity for lower level control:

public class Connection
{
    private Socket tcpSocket = null;
    public string IpAddress = "192.168.0.30";
    public int Port = 50002;

    public Connection(string ipAddress, int port)
    {
        this.IpAddress = ipAddress;
        this.Port = port;
    }

    public void Connect()
    {
        DnsEndPoint ipe = new DnsEndPoint(this.IpAddress, this.Port);
        Socket tempSocket =
            new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        tempSocket.Connect(ipe);
        if (tempSocket.Connected)
        {
            this.tcpSocket = tempSocket;
            this.tcpSocket.NoDelay = true;
            this.tcpSocket.
            //this.tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive,true);
            Console.WriteLine("Successfully connected.");
        }
        else
        {
            Console.WriteLine("Error.");
        }

    }

    public void Disconnect()
    {
        this.tcpSocket.Disconnect(true);
        this.tcpSocket.Dispose();
        Console.WriteLine("Successfuly closed.");
    }

    public string SendCommand()
    {
        string path = @"C:\Users\me\Desktop\request.json";
        string request = File.ReadAllText(path);
        Byte[] bytesSent = Encoding.UTF8.GetBytes(request);
        this.tcpSocket.Send(bytesSent);
        this.tcpSocket.Shutdown(SocketShutdown.Send);
        var respBytes = ReceiveAll();
        string s = System.Text.Encoding.UTF8.GetString(respBytes, 0, respBytes.Length);
        return s;
    }

    public byte[] ReceiveAll()
    {
        var buffer = new List<byte>();
        var currByte = new Byte[1];
        var byteCounter = this.tcpSocket.Receive(currByte, currByte.Length, SocketFlags.None);
        while (this.tcpSocket.Available > 0)
        {
            currByte = new Byte[1];
            byteCounter = this.tcpSocket.Receive(currByte, currByte.Length, SocketFlags.None);
            if (byteCounter.Equals(1))
            {
                buffer.Add(currByte[0]);
            }
        }

        return buffer.ToArray();
    }

}

Console app:

    static void Main(string[] args)
    {
        Connection s = new Connection();
        s.Connect();
        Console.WriteLine(s.SendCommand());
        Console.WriteLine(s.SendCommand());
        Thread.Sleep(5000);
        s.Disconnect();
        Console.ReadKey();
    }

This approach works once. The first time I call send command. It doesn't the second time (throws an exception), because I call socket.Shutdown() on Send in my SendCommand(). I do so because of this post:

TCPClient not receiving data

However, there doesn't seem to be a way to re-enable the ability to Send after calling Shutdown(). So now I just don't know if it's even possible to keep a tcp connection open if you have to both read and write. Moreover, I can't really find a useful example online. Does anyone know how to do so in .NET? Is this even possible?

CodePudding user response:

TCP/IP is a streaming protocol. To pass messages with it you need a “framing protocol” so peers can determine when a message is finished.

One simple way to signal the end of a message is to close the socket when you’ve sent the last byte. But this prevents socket reuse. See the evolution of HTTP for an example of this.

If this is what your device does, there’s no way to reuse a socket.

CodePudding user response:

If it is possible to keep the connection open for more messages depends on the application protocol. There is no way to enforce this if the protocol does not supports it. Thus, ask the vendor or look into the protocol specification (if it exists) for information if and how this is supported.

However, there doesn't seem to be a way to re-enable the ability to Send after calling Shutdown().

There is no way. TCP write shutdown means that one does not want to send any more information. It is impossible to take this back. If the protocol supports multiple message exchanges then it needs to have a different way to detect the end of a message than calling Shutdown.

  • Related