Fundamentals of TCP/UDP programming

Keywords: OpenCV Embedded system Single-Chip Microcomputer

catalogue

1, Foreword

(1) Socket socket

(2) TCP

(3) UDP

2, C # write a simple hello world program on the command line / console

(1) C # create console application

  (2) C # implements window output helloworld

(3) C# console program uses UDP socket to send messages

(4) C# window program uses TCP socket to send messages

1, Foreword

(1) Socket socket

    Socket is a programming interface (network programming interface).
    It is used to realize two-way communication between applications on different hosts on the network.
    Socket is a special file descriptor, which means that we can use socket to realize network communication. We can use write/read.
    
    To realize Internet communication, at least one pair of sockets is required, one of which is running on the client socket and the other is running
    Server socket
        
    Socket s can be divided into three categories:
        1)     Streaming socket (sock_stream)
            Streaming sockets are used to provide connection oriented and reliable data transmission services.
            It is mainly aimed at the application where the transport layer protocol is TCP protocol.
            
        2)     Datagram socket (SOCK_DGRAM)
            Datagram socket provides a connectionless service (it does not guarantee the reliability of data transmission).
            Mainly for applications where the transport layer protocol is UDP protocol.
            
        3)     Raw socket (SOCK_RAW)
            The original socket can directly skip the transport layer and read unprocessed IP packets.
            The streaming socket can only read the data of TCP protocol, and the datagram socket can only read the data of UDP protocol.
            Therefore, if you want to access data sent by other protocols, you must use the original socket.
 

(2) TCP

TCP protocol provides end-to-end service. The end-to-end service provided by TCP protocol is to ensure that information can reach the destination address. It is a connection oriented protocol.
Server side general steps of TCP programming
① Create a socket and use the function socket()
② Bind the IP address, port and other information to the socket, and use the function bind()
③ Enable listening and use the function listen()
④ To receive the connection from the client, use the function accept()
⑤ Send and receive data using the functions send() and recv(), or read() and write()
⑥ Close the network connection;
⑦ Turn off monitoring;
General steps of TCP programming client
① Create a socket and use the function socket()
② Set the IP address, port and other properties of the other party to be connected
③ To connect to the server, use the function connect()
④ Send and receive data using the functions send() and recv(), or read() and write()
⑤ Close network connection

(3) UDP

UDP protocol provides an end-to-end service different from TCP protocol. The end-to-end transmission service provided by UDP protocol is best effort, that is, UDP socket will transmit information as much as possible, but it does not guarantee that the information will successfully reach the destination address, and the order of information arrival is not necessarily consistent with its sending order.
Server side general steps of UDP programming
① Create a socket and use the function socket()
② Bind the IP address, port and other information to the socket, and use the function bind()
③ Receive data circularly, using the function recvfrom()
④ Close network connection
General steps of UDP programming client
① Create a socket and use the function socket()
② Set the IP address, port and other properties of the other party
③ Send data with the function sendto()
④ Close network connection

2, C # write a simple hello world program on the command line / console

(1) C # create console application

Open VS2019 and create an empty console application

  Add helloworld output to the main function

Console.WriteLine("Hello World!");
            Console.ReadKey();

  Operation effect:

  (2) C # implements window output helloworld

  Create project

 

add controls

Add a button and textbox

Double click the button automatically generates a click event, calling the showMsg() function in the click event, and the showMsg function is written as follows

void showMsg()
        {
            //Add HelloWorld to a text control
            textBox1.AppendText("Hello World!" + "\t\n");
        }

  The operation effect is as follows

(3) C# console program uses UDP socket to send messages

Create a new console program, and write the server-side code as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int recv;
            byte[] data = new byte[1024];

            //Get the local IP and set the TCP port number         
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //Bind network address
            newsock.Bind(ip);

            Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName());

            //Waiting for client connection
            Console.WriteLine("Waiting for a client");

            //Get client IP
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)(sender);
            recv = newsock.ReceiveFrom(data, ref Remote);
            Console.WriteLine("Message received from {0}: ", Remote.ToString());
            Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));

            //After the client connection is successful, send a message
            string welcome = "Hello ! ";

            //Conversion between string and byte array
            data = Encoding.UTF8.GetBytes(welcome);

            //Send message
            newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
            while (true)
            {
                data = new byte[1024];
                //Receive information
                recv = newsock.ReceiveFrom(data, ref Remote);
                Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
                //newsock.SendTo(data, recv, SocketFlags.None, Remote);
            }
        }
    }
}

  Create a new console application and write client code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace UDP
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            string input, stringData;

            //Build TCP server
            Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());

            //Set the service IP (this IP address is the IP address of the server) and set the TCP port number
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("10.160.137.1"), 8001);

            //Define network type, data connection type and network protocol UDP
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            string welcome = "Hello! ";
            data = Encoding.UTF8.GetBytes(welcome);
            server.SendTo(data, data.Length, SocketFlags.None, ip);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;

            data = new byte[1024];
            //For non-existent IP addresses, add this line of code to remove the blocking mode restriction within the specified time
            int recv = server.ReceiveFrom(data, ref Remote);
            Console.WriteLine("Message received from {0}: ", Remote.ToString());
            Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
            int i = 0;
            while (true)
            {
                string s = "hello cqjtu!Heavy handed IOT class 2019" + i;
                Console.WriteLine(s);
                server.SendTo(Encoding.UTF8.GetBytes(s), Remote);
                if (i == 50)
                {
                    break;
                }
                i++;
            }
            Console.WriteLine("Stopping Client.");
            server.Close();
        }
    }
}

  Open the command line, enter ipconfig, find the local Ipv4 address, and change the address of this line to your local address

 //Set the service IP (this IP address is the IP address of the server) and set the TCP port number
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("10.160.137.1"), 8001);

  Operation results

(4) C# window program uses TCP socket to send messages

Single thread

  Create a new window program to realize the following window layout

Button_click() and showMsg code

private void Button1_Click(object sender, EventArgs e)
        {
try{
            Socket socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Any;
            //Create port object
            IPEndPoint point = new IPEndPoint(ip, 8001);
            //binding
            socketwatch.Bind(point);

            showMsg("Monitoring succeeded!");
            socketwatch.Listen(10);

            //Waiting for client connection
            Socket socketSend = socketwatch.Accept();
            showMsg(socketSend.RemoteEndPoint.ToString() + ":" + "Connection succeeded!");
 }
            catch
            {
                showMsg("Listening failed");
            }
        }
 private void showMsg(string v)
        {
            textBox1.AppendText(v + "\r\n");
        }

Operation results

  Multithreading

  Such an interface is designed on the basis of the original

Create a new window application. The window design is the same as above

  Server side code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Listening
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //When you click start listening, the server creates a Socket responsible for listening for IP address and port number
                Socket socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Any;
                //Create port object
                IPEndPoint point = new IPEndPoint(ip, 8001);
                //binding
                socketwatch.Bind(point);

                showMsg("Monitoring succeeded!");
                socketwatch.Listen(10);
                //Create a thread
                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketwatch);

            }
            catch
            {
                showMsg("Listening failed");
            }

        }
        Socket socketSend;
        //Waiting for client connection
        void Listen(Object o)
        {
            try
            {
                Socket socketwatch = o as Socket;
                while (true)
                {
                    //Waiting for client connection
                    socketSend = socketwatch.Accept();
                    showMsg(socketSend.RemoteEndPoint.ToString() + ":" + "Connection succeeded!");
                    //Start a new thread to continuously receive client information
                    Thread th = new Thread(Receive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
            }
            catch
            { }
        }
        //Receive information sent by the client
        void Receive(Object o)
        {
            try
            {
                Socket socketSend = o as Socket;
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    showMsg(socketSend.RemoteEndPoint + ":" + str);
                }
            }
            catch
            { }
        }
        void showMsg(string str)
        {
            textBox1.AppendText(str + "\r\n");
        }
        //The server sends a message to the client
        private void button2_Click(object sender, EventArgs e)
        {
            string str = textBox2.Text;
            Console.WriteLine(str);
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
        }
    }
}

  Client code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Connect
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socketSend;
        private void button1_Click(object sender, EventArgs e)
        {
            socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint point = new IPEndPoint(IPAddress.Parse("10.160.137.1"), 8001);
            socketSend.Connect(point);
            showMsg("Connection succeeded!");
            Thread th = new Thread(Receive);
            th.IsBackground = true;
            th.Start();
        }
        //The client receives messages sent by the server
        void Receive()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    showMsg(socketSend.RemoteEndPoint + ":" + str);
                }
            }
            catch
            { }
        }
        void showMsg(string s)
        {
            textBox1.AppendText(s + "\r\n");
        }
        //The client sends a message to the server
        private void button2_Click(object sender, EventArgs e)
        {
            string str = textBox2.Text;
            int j;
            for (j = 0; j < 50; j++)
            {
                string str1 = str + j;
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str1);
                socketSend.Send(buffer);
            }
        }
    }
    }

  Realization effect

3, Reference articles

socket _qq_847607340 blog - CSDN blog _socketsocket

C # using socket to send data # Harriet's blog CSDN blog

Posted by geoldr on Mon, 22 Nov 2021 13:40:57 -0800