C#编程和网络编程入门

一、用C#编写一个命令行/控制台hello world程序

打开vs2019,新建一个C#控制台应用,写入下列代码

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();
        }
    }
}

运行,得到结果
在这里插入图片描述

命令行编程

将csc文件路径加入环境变量path中
我的路径为:E:\vs\MSBuild\Current\Bin\Roslyn
再打开命令行窗口,输入csc,出现下图效果即为成功
在这里插入图片描述
找到刚刚编写的helloworld程序.cs文件所在文件所在位置,用cmd快速进入当前路径
编译.cs文件为.exe可执行文件

csc Program.cs

执行

Program.exe

结果如下
在这里插入图片描述

网络UDP编程

在vs中创建一个c#的控制台程序,命名为client,代码如下

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


namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            int j = 0;
            while (j < 50)
            {
                Console.WriteLine("hello cqjtu!重交物联2018级");
                j++;
            }
            UdpClient client = new UdpClient("127.0.0.1", 8323);
            Console.WriteLine("正在准备发送数据!");
            try
            {
                while (j>0)
                {
                    string str = "hello cqjtu!重交物联2018级";
                    byte[] sendBytes = Encoding.Default.GetBytes(str);
                    client.Send(sendBytes, sendBytes.Length);
                    j--;  
                }
            }
           
            catch (Exception e)
            {
                
                Console.WriteLine(e);
            }
            finally
            {
                client.Close();
            }
            Console.WriteLine("数据发送成功!");
            Console.Read();
        }
    }
}

在室友的vs中新建一个程序,命名为server,代码如下

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

namespace server
{
    class Program
    {
        static void Main(string[] args)
        {
            UdpClient udpRec = new UdpClient(8323);
            Console.WriteLine("服务器已开启!");
            try
            {
                while (true)
                {
                    IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    byte[] recBytes = udpRec.Receive(ref remoteIpEndPoint);
                    string returnData = Encoding.Default.GetString(recBytes);
                    Console.WriteLine("接收到的数据是:" + returnData);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                udpRec.Close();
            }
        }
    }
}

分别运行,运行结果如下
在这里插入图片描述
在这里插入图片描述

二、用C#编写一个简单的Form窗口程序

创建一个c#窗体程序,写入代码

using System;
using System.Text;
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 = 8080;//和本机绑定的端口号
        IPAddress ip = IPAddress.Parse("192.168.8.100");//本机ip
        IPAddress remoteip = IPAddress.Parse("192.168.8.102");//远程主机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
            remoteip = ip;*/
            //IPAddress remoteip = IPAddress.Parse("192.168.43.208");

        }

        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_1(object sender, EventArgs e)
        {
            //remoteip = IPAddress.Parse(txt_IPAddress.Text);
            Thread myThread = new Thread(SendMessage);
            myThread.IsBackground = true;
            myThread.Start(textBox1.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);
                textBox1.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 (textBox1.InvokeRequired)
            {
                ClearTextBoxDelegate d = ClearTextBox;
                textBox1.Invoke(d);
            }
            else
            {
                textBox1.Clear();
                textBox1.Focus();
            }
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            this.Close();
        } 
    }
}

选择另一台电脑重复上两个步骤(注意更改ip地址)
执行效果
在这里插入图片描述
在这里插入图片描述

三、安装wireshark 抓包软件,抓取程序发送的网络包,对数据帧结构进行分析。

在官网下载wireshark安装,这里我下载的是2.6.4版本
从跟踪中选择一个 UDP 数据包。从此数据包中,确定 UDP 标头中有多少字段,并为这些字段命名,抓取一个包
在这里插入图片描述
在这里插入图片描述
UDP 的标头有 4 个字段,一共 8 byte,各字段分别为:
Source Port:源端口号
Destination Port:目的端口号
Length:长度
Checksum:校验和

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值