目录
本过程使用的工具:
Visual Studio 2019
Wireshark
一、C#实现控制台helloworld
1.项目创建
2.编写代码
using System;
namespace Console_1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
3.结果
二、C#实现窗口helloworld
1.创建项目
2.编写代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForm_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//通过点击实际完成数据的添加显示
showMsg();
}
void showMsg()
{
//向文本控件中添加HelloWorld
textBox1.AppendText("Hello World!" + "\r\n");
}
}
}
3.结果
三、C#控制台利用UDP套接字实现消息的发送
1.服务器端代码UDPServer
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Console_2
{
class UDP
{
class Program
{
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
//得到本机IP,设置TCP端口号
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//绑定网络地址
newsock.Bind(ip);
Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName());
//等待客户机连接
Console.WriteLine("Waiting for a client");
//得到客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {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);
while (true)
{
data = new byte[1024];
//接收信息
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
//newsock.SendTo(data, recv, SocketFlags.None, Remote);
}
}
}
}
}
2.步骤
①实例化并设置socket实例对象
创建ip地址和端口:
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);
绑定监听地址:
newsock.Bind(ip);
②连接
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
获取客户端的ip,来建立联系
③接收客户端的发送过来的消息
recv = newsock.ReceiveFrom(data, ref Remote);
3.客户端代码UDPClient
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Console_3
{
class Program
{
static void Main(string[] args)
{
byte[] data = new byte[1024];
string input, stringData;
//构建TCP 服务器
Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());
//设置服务IP(这个IP地址是服务器的IP),设置TCP端口号
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("169.254.160.18"), 8001);
//定义网络类型,数据连接类型和网络协议UDP
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "你好! ";
data = Encoding.UTF8.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ip);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
//对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制
int recv = server.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}: ", Remote.ToString());
Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
int i = 0;
while (true)
{
string s = "hello cqjtu!重交物联2019级" + i;
Console.WriteLine(s);
server.SendTo(Encoding.UTF8.GetBytes(s), Remote);
if (i == 50)
{
break;
}
i++;
}
Console.WriteLine("Stopping Client.");
server.Close();
}
}
}
4.结果(这里是在自己电脑上测试)
四、C#控制台利用TCP套接字实现消息的发送
(1)代码
分别两个项目
1.客户端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket socketSend;
private void button1_Click(object sender, EventArgs e)
{
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint point = new IPEndPoint(IPAddress.Parse("169.254.160.18"), 8001);
socketSend.Connect(point);
showMsg("连接成功!");
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start();
}
void Receive()
{
try
{
while (true)
{
byte[] buffer = new byte[1024 * 1024 * 2];
int r = socketSend.Receive(buffer);
if (r == 0)
{
break;
}
string str = Encoding.UTF8.GetString(buffer, 0, r);
Invoke(new Action(() => {//在线程里修改界面
showMsg(socketSend.RemoteEndPoint + ":" + str);
}));
}
}
catch
{ }
}
void showMsg(string str)
{
textBox2.AppendText(str + "\r\n");
}
private void button2_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
socketSend.Send(buffer);
}
}
}
2.服务器
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinServer
{
public partial class Form1 : Form
{
string str = "没有改变";
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
Console.WriteLine(str);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
socketSend.Send(buffer);
}
void showMsg(string str)
{
textBox2.AppendText(str + "\r\n");
}
void Receive(Object o)
{
try
{
Socket socketSend = o as Socket;
while (true)
{
byte[] buffer = new byte[1024 * 1024 * 2];
int r = socketSend.Receive(buffer);
if (r == 0)
{
break;
}
string str = Encoding.UTF8.GetString(buffer, 0, r);
Invoke(new Action(() => {//在线程里修改界面
showMsg(socketSend.RemoteEndPoint + ":" + str);
}));
}
}
catch
{ }
}
Socket socketSend;
//等待客户端的连接
void listen(Object o)
{
try
{
Socket socketwatch = o as Socket;
int i = 0;
while (true)
{
//等待客户端的连接
socketSend = socketwatch.Accept();
str = socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!";
Invoke(new Action(() => {//在线程里修改界面
showMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
}));
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start(socketSend);
}
}
catch
{ }
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//点击开始侦听的时候,服务器创建一个负责监听IP地址跟端口号的Socket
Socket socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
//创建端口对象
IPEndPoint point = new IPEndPoint(ip, 8001);
//绑定
socketwatch.Bind(point);
showMsg("监听成功!");
socketwatch.Listen(10);
//创建一个线程
Thread th = new Thread(listen);
th.IsBackground = true;
th.Start(socketwatch);
}
catch
{
showMsg("监听失败");
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
(2)窗口
1.服务器窗口
2.客户端窗口
(3)结果
先点击监听,再点击连接就可以发送消息了
五、单线程扫描
1.代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Win_dansaomiao
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int port;//记录当前扫描的端口号
private string Address;//记录扫描的系统地址
private bool[] done = new bool[65536];//记录端口的开放状态
private int start;//记录扫描的起始端口
private int end;//记录扫描的结束端口
private bool OK;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
label4.Text = textBox2.Text;
label5.Text = textBox3.Text;
progressBar1.Minimum = Int32.Parse(textBox2.Text);
progressBar1.Maximum = Int32.Parse(textBox3.Text);
listBox1.Items.Clear();
listBox1.Items.Add("端口扫描器v1.0.");
listBox1.Items.Add("");
PortScan();
}
private void PortScan()
{
start = Int32.Parse(textBox2.Text);
end = Int32.Parse(textBox3.Text);
//判断输入端口是否合法
if ((start >= 0 && start <= 65536) && (end >= 0 && end <= 65536) && (start <= end))
{
listBox1.Items.Add("开始扫描:这个过程可能需要等待几分钟!");
Address = textBox1.Text;
for (int i = start; i <= end; i++)
{
port = i;
Scan();
progressBar1.Value = i;
label5.Text = i.ToString();
}
while (!OK)
{
OK = true;
for (int i = start; i <= end; i++)
{
if (!done[i])
{
OK = false;
break;
}
}
}
listBox1.Items.Add("扫描结束!");
}
else
{
MessageBox.Show("输入错误,端口范围为[0,65536]");
}
}
private void Scan()
{
int portnow = port;
done[portnow] = true;
TcpClient objTCP = null;
try
{
objTCP = new TcpClient(Address, portnow);
listBox1.Items.Add("端口" + portnow.ToString() + "开放");
}
catch
{
}
}
}
}
2.窗口
3.结果
单线程比较慢,扫五个就花了10s左右
六、多线程扫描
1.代码
在这里插入代码片
2.窗口(与上面相同)
3.结果
端口增加了,但是几秒就扫完了!
七、wireshark抓包
1.C#控制台UDP套接字
2.C#控制台TCP套接字
八、总结
学习了C#开发window窗口应用,勉强算入门了,了解了一些窗口的创建,和窗口组件使用。多线程的应用比单线程快很多,推荐使用。