Petr Faltus development

C# network communication over TCP socket

Petr Faltus development

Example source code in Microsoft .NET csharp how to communicate in IPv4 over network TCP socket. The sender and the receiver.

NetTCPreceiver.cs

GitHub repository: network-socket-communication-source-codes

git clone https://github.com/petrfaltus/network-socket-communication-source-codes.git

Directories to NetTCPreceiver.cs in the repository: csharp/src

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace NetTCPreceiver
{
    public class Program
    {
        private static readonly int RECEIVER_PORT = 10000;
        private static readonly int RECEIVED_MESSAGES_MAX = 10;
        private static readonly int BUFFER_SIZE = 4096;

        public static void Main(string[] args)
        {
            Console.WriteLine("TCP IPv4 stream socket receiver");

            try
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Console.WriteLine("- socket created");

                IPEndPoint receiver = new IPEndPoint(IPAddress.Any, RECEIVER_PORT);

                socket.Bind(receiver);
                Console.WriteLine("- socket bound on port {0}", RECEIVER_PORT);

                socket.Listen(RECEIVED_MESSAGES_MAX);
                Console.WriteLine("- socket is listening for max {0} messages", RECEIVED_MESSAGES_MAX);

                bool stop = false;
                while (stop == false)
                {
                    Socket msgsock = socket.Accept();
                    Console.WriteLine("- socket accepted request");

                    IPEndPoint peer = (IPEndPoint)msgsock.RemoteEndPoint;
                    IPEndPoint local = (IPEndPoint)msgsock.LocalEndPoint;
                    Console.WriteLine("- peer connect from {0}:{1} on {2}:{3}", peer.Address, peer.Port, local.Address, local.Port);

                    byte[] buffer = new byte[BUFFER_SIZE];
                    int received_length = msgsock.Receive(buffer);
                    string msg = Encoding.ASCII.GetString(buffer, 0, received_length);
                    Console.WriteLine("- message {0}B of {1}B received", msg.Length, received_length);
                    Console.WriteLine("|{0}|", msg);

                    if (msg.Equals("stop"))
                    {
                        // received message "stop" to stop the receiver
                        stop = true;
                    }

                    msgsock.Close();
                    Console.WriteLine("- socket closed request");
                }

                socket.Close();
                Console.WriteLine("- socket closed");
            }
            catch (Exception ex)
            {
                Console.WriteLine("- {0}", ex.Message);
            }
        }
    }
}

NetTCPsender.cs

Directories to NetTCPsender.cs in the repository: csharp/src

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace NetTCPsender
{
    public class Program
    {
        private static readonly string RECEIVER_ADDRESS = "127.0.0.1";
        private static readonly int RECEIVER_PORT = 10000;

        public static void Main(string[] args)
        {
            Console.WriteLine("TCP IPv4 stream socket sender");

            try
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Console.WriteLine("- socket created");

                IPAddress receiver_address = IPAddress.Parse(RECEIVER_ADDRESS);
                IPEndPoint receiver = new IPEndPoint(receiver_address, RECEIVER_PORT);

                socket.Connect(receiver);
                Console.WriteLine("- connected to {0}:{1}", receiver_address, RECEIVER_PORT);

                IPEndPoint peer = (IPEndPoint)socket.RemoteEndPoint;
                IPEndPoint local = (IPEndPoint)socket.LocalEndPoint;
                Console.WriteLine("- for {0}:{1} bound on {2}:{3}", peer.Address, peer.Port, local.Address, local.Port);

                string msg;
                if (args.Length > 0)
                    msg = args[0]; // message is the first parameter, for example "stop" to stop the receiver
                else
                {
                    DateTime now = DateTime.Now;
                    msg = string.Format("This is C# message sent at {0} in {1}", now.ToString("d.M.yyyy"), now.ToString("H:mm:ss"));
                }
                Console.WriteLine("|{0}|", msg);

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

                int sent_length = socket.Send(buffer);
                Console.WriteLine("- message {0}B of {1}B sent", sent_length, msg.Length);

                socket.Close();
                Console.WriteLine("- socket closed");
            }
            catch (Exception ex)
            {
                Console.WriteLine("- {0}", ex.Message);
            }
        }
    }
}

  Previous example All examples Following example  

  

🤝 Your IP address is 3.238.98.39


💻💽💾 Useful examples and tools for home and professional programming.


© Petr Faltus - 2021