none
Simple TCP messageing sample RRS feed

  • Question

  • I am in the process of developing an application that will need to talk back and forth with another server application.

    I have never used the TCP... classes and am looking for a sample (That actually compiles for .NET 4.8)

    Wondering if someone can point me in the right direction?

    Thanks in advance.


    • Edited by BNIinc Tuesday, July 28, 2020 1:41 PM
    Tuesday, July 28, 2020 1:40 PM

Answers

All replies

  • IPC can be done via TCP but that would be very low level and only if you really need total control over the communication. If you just need IPC then look into WCF, REST APIs or equivalent. For a simple example of using TCP messaging refer to TcpListener for the server side. For the client refer to TcpClient. These would be the simplest, non-production examples. You can expand from there.

    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, July 28, 2020 2:10 PM
    Moderator
  • Hi

    I do not know your actual requirement . As per @CoolDadTx suggest is good for you.

    Another scenario is signalR .May help the bellow url

    https://www.codeproject.com/Articles/5162436/Simple-SignalR-Server-and-Client-Applications-Demo

    Thanks and regards

    Tuesday, July 28, 2020 3:50 PM
  • Hi BNIinc,
    Based on your description, I made a simple code example you can refer to.
    First, I create a socket and set up a listener server node, which starts listening for all incoming messages via a predefined IP and protocol. 
    Then I create a client application that will send the message to the listener server and read it.
    Step one: Create a Listener
    You can create a .NET Core Console app and write the following code:

    static int Main(string[] args)
    {
        StartServer();
        return 0;
    }
    public static void StartServer()
    {
        // Get Host IP Address that is used to establish a connection  
        // In this case, we get one IP address of localhost 
        // If a host has multiple addresses, you will get a list of addresses  
        IPHostEntry host = Dns.GetHostEntry("localhost");
        IPAddress ipAddress = host.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
        try
        {
            // Create a Socket that will use Tcp protocol      
            Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            // A Socket must be associated with an endpoint using the Bind method  
            listener.Bind(localEndPoint);
            // Specify how many requests a Socket can listen before it gives Server busy response.  
            // We will listen 10 requests at a time  
            listener.Listen(10);
    
            Console.WriteLine("Waiting for a connection...");
            Socket handler = listener.Accept();
    
            // Incoming data from the client.    
            string data = null;
            byte[] bytes = null;
    
            while (true)
            {
                bytes = new byte[1024];
                int bytesRec = handler.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                if (data.IndexOf("<EOF>") > -1)
                {
                    break;
                }
            }
    
            Console.WriteLine("Text received : {0}", data);
    
            byte[] msg = Encoding.ASCII.GetBytes(data);
            handler.Send(msg);
            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    
        Console.WriteLine("\n Press any key to continue...");
        Console.ReadKey();
    }

    Step two: Create a Client.
    You can create another .NET Core console application and write the following code:

    static int Main(string[] args)
    {
        StartClient();
        return 0;
    }
    public static void StartClient()
    {
        byte[] bytes = new byte[1024];
    
        try
        {
            // Connect to a Remote server  
            // Get Host IP Address that is used to establish a connection  
            // In this case, we get one IP address of localhost 
            // If a host has multiple addresses, you will get a list of addresses  
            IPHostEntry host = Dns.GetHostEntry("localhost");
            IPAddress ipAddress = host.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
    
            // Create a TCP/IP  socket.    
            Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
    
            // Connect the socket to the remote endpoint. Catch any errors.    
            try
            {
                // Connect to Remote EndPoint  
                sender.Connect(remoteEP);
    
                Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
    
                // Encode the data string into a byte array.    
                byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
    
                // Send the data through the socket.    
                int bytesSent = sender.Send(msg);
    
                // Receive the response from the remote device.    
                int bytesRec = sender.Receive(bytes);
                Console.WriteLine("Echoed test : {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
                    
                // Release the socket.    
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();
                Console.ReadKey();
    
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }
    
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    Step three: Test and Run
    Now build both projects and run both applications from the command line. You will see the message sent by the client is read and displayed by the listener. 
    Once client runs, you will see the message is sent to the server.
    The result:
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, July 29, 2020 5:06 AM
  • I wrote a blog post a while ago about Event-Driven TCP:

    https://geek-goddess-bonnie.blogspot.com/2018/12/event-driven-tcp.html

    My post has an explanation of how this works, along with links to code samples that you can download. This is basically code that I've used in production systems, although I think what I've posted is not quite what I'm currently using (I've made changes along the way since that blog item was posted).

    But, it'll get you going in a good direction initially, I think.

    Have fun!  =0)


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Marked as answer by BNIinc Monday, August 3, 2020 10:44 AM
    Sunday, August 2, 2020 12:56 AM
    Moderator