知识屋:更实用的电脑技术知识网站
所在位置:首页 > 科技  > 软件

C#编程和网络编程入门

发表时间:2022-03-24来源:网络

C#数据发送

一、 C#实现hello world二、 C#实现窗口三、 C#控制台程序,用UDP实现消息发送使用Wireshark抓包

一、 C#实现hello world

1、项目创建

3、在test1中编写代码

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelloWorldConsole { class Program { static void Main(string[] args) { //实现helloworld语句的输出,相当于C语言中的printf Console.WriteLine("Hello World!"); } } }

4、效果

二、 C#实现窗口

1、项目创建

2、代码编写

using System; using System.Windows.Forms; namespace HelloworldWindow { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //通过点击实际完成数据的添加显示 showMsg(); } void showMsg() { //向文本控件中添加HelloWorld textBox1.AppendText("Hello World!" + "\t\n"); } } }

三、 C#控制台程序,用UDP实现消息发送

1、服务器端代码

using System; using System.Windows.Forms; namespace HelloworldWindow { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //通过点击实际完成数据的添加显示 showMsg(); } void showMsg() { //向文本控件中添加HelloWorld textBox1.AppendText("Hello World!" + "\t\n"); } } }

步骤:
1.1、实例化并设置socket实例对象
创建ip地址和端口:

IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);

绑定监听地址:

newsock.Bind(ip);

1.2、连接

IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
获取客户端的ip,来建立联系

1.3、接收客户端的发送过来的消息

recv = newsock.ReceiveFrom(data, ref Remote);

2、客户端代码

using System; using System.Windows.Forms; namespace HelloworldWindow { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //通过点击实际完成数据的添加显示 showMsg(); } void showMsg() { //向文本控件中添加HelloWorld textBox1.AppendText("Hello World!" + "\t\n"); } } }

3、实现客户端向服务器发送消息效果

使用Wireshark抓包

收藏
  • 人气文章
  • 最新文章
  • 下载排行榜
  • 热门排行榜