Introduction to C# Programming and Network Programming

Tools: vs2017

1. Use C# to write a command line/console hello world program

Console application

Open vs2017, create a new C# console application and
write the following code

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

namespace ConsoleApp1
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            string s = "hello cqjtu!重交物联2018级";
            //因为下面要使用StringBuilder的Append函数
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 50; i++)
            {
    
    
                sb.Append(s);
            }
            //将StringBuilder转换为string,并写入
            Console.WriteLine(sb.ToString());
            //控制台显示
            Console.ReadLine();
        }
    }
}

display effect
Insert picture description here

Command line programming

1. Configure environment variables.
Find the file location of csc.exe and add its path to the environment variable path.
For example, my csc.exe is in D:\visual studio install\MSBuild\15.0\Bin\Roslyn and
then open the command line window and enter csc, if the following picture appears, it means success.
Insert picture description here
Find the location of the .cs file of the helloworld program, and use cmd to quickly enter the current path.
Insert picture description here
Compile the .cs file into an .exe executable file

csc Program.cs

carried out

Program.exe

Insert picture description here

Two, network UDP programming

Realization function: Open the program and send the information printed by the helloworld program to another computer.
UDP programming is for connectionless, and there is no need to establish a connection between the client and the server.
Open the new c# console project udp_server of vs2017, and put udp_server in Replace the code in Program.c with:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

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

            //得到本机IP,设置TCP端口号         
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //绑定网络地址
            server.Bind(ip);

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

            //等待客户机连接
            Console.WriteLine("Waiting for a client");

            //得到客户机IP
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)(sender);
            recv = server.ReceiveFrom(data, ref Remote);
            Console.WriteLine("Message received from {0}: ", Remote.ToString());
            Console.WriteLine(Encoding.Default.GetString(data, 0, recv));

            //客户机连接成功后,发送信息
            string welcome = "连接成功 ";

            //字符串与字节数组相互转换
            data = Encoding.Default.GetBytes(welcome);

            //发送信息 
            server.SendTo(data ,Remote);



            while (true)
            {
    
    
                data = new byte[1024];
                //发送接收信息
                //从客户机接受消息
                recv = server.ReceiveFrom(data, ref Remote);
                //将字节流信息转换为字符串
                string Data = Encoding.Default.GetString(data, 0, recv);
                //将字符串输出到屏幕上
                Console.WriteLine(Data);
                // Console.WriteLine(Encoding.Default.GetString(data, 0, recv));
                /*
                //定义字符串input
                string input;
                //读取屏幕上的字符串
                input = Console.ReadLine();
                if (input == "exit")
                    break;
                //将input发送至客户机
                server.SendTo(Encoding.Default.GetBytes(input),Remote);*/
            }
            server.Close();
        }

    }
}

Close the current project and create a new c# console project udp_client, replace the code in Program.c in udp_client with:

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

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

            //构建TCP 服务器
            Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());

            //设置服务IP,设置TCP端口号
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001);

            //定义网络类型,数据连接类型和网络协议UDP
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            string welcome = "连接成功!";
            //字符串与字节数组相互转换
            data = Encoding.Default.GetBytes(welcome);
            //发送信息
            client.SendTo(data,ip);

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;

            data = new byte[1024];
            //对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制
            //接受信息
            int recv = client.ReceiveFrom(data, ref Remote);
            //输出服务端ip
            Console.WriteLine("Message received from {0}: ", Remote.ToString());
            //输出接受到的信息
            Console.WriteLine(Encoding.Default.GetString(data, 0, recv));
            while (true)
            {
    
    
                //读取屏幕的字符串存入input中
                input = Console.ReadLine();
                if (input == "exit")
                    break;
                //将input中的字符串发送至服务端
                for (int i=0;i<50;i++)
                {
    
    
                    client.SendTo(Encoding.Default.GetBytes(input), Remote);
                }

                /*
                data = new byte[1024];
                //将接受自服务端的信息存入recv中
                recv = client.ReceiveFrom(data, ref Remote);
                //将字节流转为字符串
                string Data = Encoding.Default.GetString(data, 0, recv);
                //将Date中的数据打印到屏幕上
                Console.WriteLine(Data);*/
            }
            //输入exit后,屏幕打印下列字符串
            Console.WriteLine("Stopping Client.");
            //关闭服务端
            client.Close();
        }

    }
}

Insert picture description here
1. Note that the ip pointed by the arrow is the computer ip of the server, which can be obtained by the ipconfig command in the cmd window.
2. One computer runs the server and one computer runs the client. The two computers must be in the same local area network.
3. The above program only Realize the
effect of sending data from the client to the server
Insert picture description here

Third, use VS2017 C# to write a simple Form window program

Open vs2017 to create a c# windows form application frame_udp_server,
window control:
listBpx
textBox
button
label
Insert picture description here
replace the content in Form1.cs with the following:

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


namespace frame_udp_server
{
    
    
    public partial class Form1 : Form
    {
    
    
        private UdpClient receiveUdpClient;//接收用
        private UdpClient sendUdpClient;//发送用
        private const int port = 8001;//和本机绑定的端口号
        IPAddress ip = IPAddress.Parse("192.168.43.2");//本机ip
        IPAddress remoteip = IPAddress.Parse("192.168.43.151");//远程主机ip
        public Form1()
        {
    
    
            InitializeComponent();
            
            CheckForIllegalCrossThreadCalls = false;
            /*
            //获取本机可用IP地址
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ipa in ips)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                {
                    ip = ipa;
                    break;
                }
            }
            */
            //为了在同一台机器调试,此IP也作为默认远程IP
            //IPAddress remoteip = IPAddress.Parse("192.168.43.151");

        }

        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            //创建一个线程接收远程主机发来的信息
            Thread myThread = new Thread(ReceiveData);
            myThread.IsBackground = true;
            myThread.Start();
        }

        //接收数据
        private void ReceiveData()
        {
    
    
            IPEndPoint local = new IPEndPoint(ip, port);
            receiveUdpClient = new UdpClient(local);
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
    
    
                try
                {
    
    
                    //关闭udpClient 时此句会产生异常
                    byte[] receiveBytes = receiveUdpClient.Receive(ref remote);
                    string receiveMessage = Encoding.Unicode.GetString(
                        receiveBytes, 0, receiveBytes.Length);
                    listBox1.Items.Add("收到的消息:" + receiveMessage);
                }
                catch
                {
    
    
                    break;
                }
            }
        }
        //点击发送按钮发送数据
        private void button1_Click(object sender, EventArgs e)
        {
    
    
            //remoteip = IPAddress.Parse(txt_IPAddress.Text);
            Thread myThread = new Thread(SendMessage);
            myThread.IsBackground = true;
            myThread.Start(textBox2.Text);
        }
        //发送消息
        private void SendMessage(object obj)
        {
    
    
            string message = (string)obj;
            sendUdpClient = new UdpClient(0);
            byte[] bytes = Encoding.Unicode.GetBytes(message);
            IPEndPoint iep = new IPEndPoint(remoteip, port);
            try
            {
    
    
                sendUdpClient.Send(bytes, bytes.Length, iep);
                listBox1.Items.Add("发送的消息:" + message);
                textBox2.Clear();
            }
            catch (Exception ex)
            {
    
    
                listBox1.Items.Add("发送出错:" + ex.Message);
            }
        }
        delegate void AddItemDelegate(ListBox listbox, string text);
        private void AddItem(ListBox listbox, string text)
        {
    
    
            if (listbox.InvokeRequired)
            {
    
    
                AddItemDelegate d = AddItem;
                //Control.Invoke 方法 (Delegate, Object[]):
                //在拥有控件的基础窗口句柄的线程上,用指定的参数列表执行指定委托。
                listbox.Invoke(d, new object[] {
    
     listbox, text });
            }
            else
            {
    
    
                //Add:动态的添加列表框中的项
                listbox.Items.Add(text);

                //SelectedIndex属性获取单项选择ListBox中当前选定项的位置
                //Count:列表框中条目的总数
                listbox.SelectedIndex = listbox.Items.Count - 1;

                //调用此方法等效于将 SelectedIndex 属性设置为-1。 
                //可以使用此方法快速取消选择列表中的所有项。
                listbox.ClearSelected();
            }
        }
        delegate void ClearTextBoxDelegate();
        private void ClearTextBox()
        {
    
    
            if (textBox2.InvokeRequired)
            {
    
    
                ClearTextBoxDelegate d = ClearTextBox;
                textBox2.Invoke(d);
            }
            else
            {
    
    
                textBox2.Clear();
                textBox2.Focus();
            }
        }




    }
}

Note:
The ip I used for testing here is the ip of two computers in a local area network formed by my mobile phone hotspot.
In short, this program is the same as the console udp program above. To connect, it must be in the same local area network.
Insert picture description here
Close the project frame_udp_server. Create a new c# windows form application frame_udp_client, the code is the same except the local ip and remote host ip in the above picture.
Test effect:
Insert picture description here
The following is the data sent by this program captured using wireshark packet capture software
Insert picture description here

Insert picture description here
1. The UDP header has 4 fields, a total of 8 bytes, each field is:
*Source Port: source port number
*Destination Port: destination port number
*Length: length
*Checksum: checksum

2. By querying the information displayed in Wireshark's packet content field, the length of each UDP header field can be determined.
Each part is 2 byte, so the UDP header is 8 byte = 64 bit.
3. The length field indicates the number of bytes (header + data) in the UDP message segment. This is because the length of the data field in one UDP segment is different from that in another segment, so a clear length is required.
Insert picture description here

As shown in the figure, the length of the message is 26 bytes, plus 8 bytes in the header is just the length of Length

The payload is a part of the data to be transmitted, and this part is the most basic purpose of data transmission. The data transmitted with the payload is also: the data header or metadata, sometimes also called overhead data , These data are used to assist data transmission. --Baidu Encyclopedia

4. Simply put, the payload is a variable-length data part. Because the Length field occupies 2byte = 65536 bits, and 8 byte is the UDP header information. So the payload = 65536-8 = 65528 bit.
5. What is the largest possible source port number?
The two Port fields occupy 2 byte = 65536 bits, and the port number starts from 0, so the maximum port number = 65536-1 = 65535.
6. As shown in the figure, the udp protocol number is 17, and the hexadecimal number is 0x11.
Insert picture description here
7. While catching this packet, we can definitely find the reply packet, the source port and destination port of the two packets should be opposite

Reference blog:

C # UDP chat window procedure
c # forms application ---- textbox controls
the issue of class is instantiated when IPAddress parameter.
Invalid inter-thread operation
c# ListBox control

Guess you like

Origin blog.csdn.net/xianyudewo/article/details/109318426