目录
本实验所用环境:
Visual Studio 2019
Wireshark
一、用C#在屏幕上连续输出50行信息
(1)打开vs2019,选择C#控制台应用程序
(2)进入代码编辑界面输入如下代码
使用一个循环来连续输出50行信息
for (int i = 1; i < 51; i++)
{
Console.Write(" hello cqjtu!重交物联2018级\n");
}
Console.ReadLine();
(3)实现效果如下
二、利用UDP向室友电脑发送(接收)这50行消息
本人电脑作为服务端,vs选用控制台应用程序
(1)服务端代码如下
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,设置UDP端口号
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//绑定网络地址
newsock.Bind(ip);
Console.WriteLine("这里是服务器,名称为{0}", Dns.GetHostName());
//等待客户机连接
Console.WriteLine("等待客户端连接");
//得到客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine("消息来自于{0}: ", Remote.ToString());
Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
//客户端连接成功后,发送信息
string welcome = "你好 !客户端 ";
//字符串与字节数组相互转换
data = Encoding.UTF8.GetBytes(welcome);
//发送信息
newsock.SendTo(data, data.Length, SocketFlags.None, Remote);