Getting to know C# -- using socket to send data

Posted by mattsoftnet on Thu, 25 Nov 2021 20:58:05 +0100

1, Basic introduction to UDP

1,Socket

Socket is the basic operation unit of network communication supporting TCP/IP protocol. Socket can be regarded as the endpoint of two-way communication between processes between different hosts. It constitutes the programming interface within a single host and between the whole network.

How sockets work:
Communication through the Internet requires at least one pair of sockets, one of which runs on the client side, called ClientSocket, and the other runs on the server side, called ServerSocket.

The connection process between sockets can be divided into three steps: server listening, client request and connection confirmation.

2,TCP

TCP protocol provides end-to-end services. 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 # implements HelloWorld

1. Project creation


2. Code part

  • code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            //50 lines of "hello cqjtu! cj IOT 2019" are continuously output on the screen
            for(int t=0; t<50; t++)
            {
                Console.WriteLine("Hello cqjtu! cj IOT 2019");
            }
        }
        System.Console.ReadKey();
    }
}

  • Operation results:

3. Use UDP communication

  • 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 Client
{
    class Program
    {
        static void Main(string[] args)
        {
            //Prompt information
            Console.WriteLine("Press any key to start sending...");
            Console.ReadKey();
            
            int m;

            //Get ready for the link
            UdpClient client = new UdpClient();  //Instance a port
            IPAddress remoteIP = IPAddress.Parse("10.61.38.89");  //Suppose sent to this IP
            int remotePort = 11000;  //Set port number
            IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);  //Instantiate a remote endpoint 

            for(int i = 0; i < 50; i++)
            {
                //Data to send: line n: hello cqjtu! Resubmit IOT 2019
                string sendString = null;
                sendString += "The first";
                m = i+1;
                sendString += m.ToString();
                sendString += "that 's ok: hello cqjtu!cj IOT 2019";

                //Defines the byte array to send
                //Converts a string to bytes and stores it in a byte array
                byte[] sendData = null;
                sendData = Encoding.Default.GetBytes(sendString);

                client.Send(sendData, sendData.Length, remotePoint);//Send data to remote endpoint 
            }
            client.Close();//Close connection

            //Prompt information
            Console.WriteLine("");
            Console.WriteLine("The data is sent successfully. Press any key to exit...");
            System.Console.ReadKey();
        }
    }
}

  • Server 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 Server
{
    class Program
    {
        static void Main(string[] args)
        {
            int result;
            string str = "Line 50: hello cqjtu!cj IOT 2019";
            UdpClient client = new UdpClient(11000);
            string receiveString = null;
            byte[] receiveData = null;
            //Instantiate a remote endpoint. The IP and port can be specified at will. When calling client.Receive(ref remotePoint), the endpoint will be changed to the real sending endpoint 
            IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
            Console.WriteLine("Preparing to receive data...");
            while (true)
            {
                receiveData = client.Receive(ref remotePoint);//receive data  
                receiveString = Encoding.Default.GetString(receiveData);
                Console.WriteLine(receiveString);
                result = String.Compare(receiveString, str);
                if (result == 0)
                {
                    break;
                }
            }
            client.Close();//Close connection
            Console.WriteLine("");
            Console.WriteLine("After receiving data, press any key to exit...");
            System.Console.ReadKey();
        }
    }
}

  • Operation results:
    client

    Server
  • wireshark grab

3, C # use window program to send information (TCP)

1. Project creation


Initial interface:

Drag a Button and two textboxes:


textBox1 basic settings:


testBox2 basic settings:

button basic settings:

Form1 basic settings:

2. Code part

  • Client button click event:
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.Tasks;
using System.Windows.Forms;

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

        private void button_send_Click(object sender, EventArgs e)
        {
            string str = "The current time: ";
            str += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            textBox1.AppendText(str + Environment.NewLine);
            UdpClient udpSender = new UdpClient(0);
            int port = 8000;
            string host = "10.61.38.89";//My roommate's IP address
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);//Convert ip and port to IPEndPoint instance
            udpSender.Connect(host, port);
            string message = textBox2.Text;
            byte[] sendBytes = Encoding.UTF8.GetBytes(message);
            udpSender.Send(sendBytes, sendBytes.Length);
            string sendStr = textBox2.Text;
            str = "The message content: " + sendStr;
            textBox1.AppendText(str + Environment.NewLine);
            str = "Send the message to the server...";
            textBox1.AppendText(str + Environment.NewLine);
            byte[] recvStr = udpSender.Receive(ref ipe);
            string message1 = Encoding.UTF8.GetString(recvStr, 0, recvStr.Length);
            str = "The server feedback: " + message1;//Display server return information
            textBox1.AppendText(str + Environment.NewLine);
        }
    }
}
  • Server 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 Service1
{
    internal 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, 8000);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

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

            Console.WriteLine("This is the server, Host name is: {0}", Dns.GetHostName());

            //Waiting for client connection
            Console.WriteLine("Waiting for client to send data...");

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

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

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

            //Send message 
            server.SendTo(data, Remote);



            while (true)
            {
                data = new byte[1024];
                //Send and receive information
                //Accept messages from clients
                recv = server.ReceiveFrom(data, ref Remote);
                //Converts byte stream information to a string
                string Data = Encoding.Default.GetString(data, 0, recv);
                //Output string to screen
                Console.WriteLine(Data);
                // Console.WriteLine(Encoding.Default.GetString(data, 0, recv));

                //Define string input
                string input;
                //Read string on screen
                input = "Connection succeeded";
                if (input == "exit")
                    break;
                //Send input to client
                server.SendTo(Encoding.UTF8.GetBytes(input), Remote);
            }
            server.Close();
        }
    }
}
  • Operation results:
    client:

Server:

3. Wireshark packet capture

4, Summary

Successfully used C# to write a simple hello world program of command line / console and a simple Form window program, and had a certain understanding of UDP

Reference articles

C # using socket to send data

Topics: C# udp