C#使用TCP/UDP协议通信

本文详细介绍了如何在C#中使用TCP和UDP协议进行通信,包括控制台程序和Form窗口程序的实现,涵盖了创建项目、代码实现、运行结果及Wireshark抓包分析,特别强调了TCP与UDP的区别。
摘要由CSDN通过智能技术生成

一.控制台程序使用 UDP 通信

1.创建项目

在这里插入图片描述

在这里插入图片描述

2.代码

循环输出"hello cqjtu!重交物联2019级"

for (int i = 0; i < 50; i++)
            {
   
                Console.WriteLine("hello cqjtu!重交物联2019级");
            }
            System.Console.ReadKey();

3.运行结果

在这里插入图片描述

二.使用 UDP 通信

目前最普遍的服务模式是 C/S 模式,所以需要编写一个客户端 client 和一个服务端 Server ,来实现通信。

1.发送端

代码流程:
首先显示提示信息,等待使用人员操作;做好连接准备,
如:设置IP、端口号等;
for 循环发送数据;
关闭端口;显示提示信息,等待用户确认退出。
代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets; 
//注意头文件!!!使用网络协议需要引入头文件 .Net 和 .Net.Sockets)

namespace ConsoleApp1
{
   
    class Program
    {
   
        static void Main(string[] args)
        {
   
            //提示信息
            Console.WriteLine("按下任意按键开始发送...");
            Console.ReadKey();

            //做好链接准备
            UdpClient client = new UdpClient();  //实例一个端口
            IPAddress remoteIP = IPAddress.Parse("10.60.4.53");  //假设发送给这个IP
            int remotePort = 11000;  //设置端口号
            IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);  //实例化一个远程端点 

            for (int i = 0; i < 50; i++)
            {
   
                //要发送的数据:第n行:hello cqjtu!重交物联2018级
                string sendString = null;
                sendString += "hello cqjtu!重交物联2019级";

                //定义发送的字节数组
                //将字符串转化为字节并存储到字节数组中
                byte[] sendData = null;
                sendData = Encoding.Default.GetBytes(sendString);

                client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点 
            }
            client.Close();//关闭连接

            //提示信息
            Console.WriteLine("");
            Console.WriteLine("数据发送成功,按任意键退出...");
            System.Console.ReadKey();
        }
    }
}



2.接收端

代码流程:
做好连接准备,并设置结束标志;
循环接收数据;
关闭连接;显示提示信息,等待用户确定退出。
代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值