TCP/UDP编程基础
一、控制台使用UDP通信
实验内容:用C#、Java或python编写一个命令行/控制台的简单hello world程序,实现如下功能:
1.在屏幕上连续输出50行“hello cqjtu!重交物联2019级”
2.同时打开一个网络UDP 套接字,向另一台室友电脑发送这50行消息
创建项目
打开vs2019→“创建新项目”→选择“控制台应用(.NET Framework)”→完成创建
输入代码
for (int i = 0; i < 50; i++)
{
Console.WriteLine("hello cqjtu!重交物联2019级");
}
System.Console.ReadKey();
运行:
使用UDP通信
编写客户端Client和服务器Server,实现通信。
具体实现是在两台电脑上分别运行客户端代码和服务器代码,实现通信功能
发送端
流程及代码:
1.首先显示提示信息,等待使用人员操作;
2.做好连接准备,如:设置IP、端口号等;
3.for 循环发送数据;
4.关闭端口;
5.显示提示信息,等待用户确认退出。
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();
}
}
}
接收端
流程及代码:
1.做好连接准备,并设置结束标志;
2.循环接收数据;
3.关闭连接;
4.显示提示信息,等待用户确定退出。
using System;
using Syst