Socket 学习(三).2 udp 穿透 服务端 与 客户端 通讯

时间:2021-01-02 20:22:20

之前演示的 是 局域网通讯,也可以用作服务器之间的通讯,不能穿透。 想要穿透就要用 udp 了, 后续再讲解 udp 打洞 .

客户端:

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading; namespace WinFormP2pClient
{
public partial class Form1 : Form
{
public Form1()
{
CheckForIllegalCrossThreadCalls = false;// 禁止线程检查
InitializeComponent();
} private UdpClient _udpClient;
private IPEndPoint _serverIpEndPoint;
private Thread _threadReceive;
// 线程 接收
private void Button1Click(object sender, EventArgs e)
{
_udpClient = new UdpClient();//不指定自己的端口
_serverIpEndPoint = new IPEndPoint(IPAddress.Parse(textBoxIP.Text), );//服务端IP、端口 本地测试就用127.0.0.1 就好
byte[] buffer = Encoding.UTF8.GetBytes("你好");
_udpClient.Send(buffer, buffer.Length, _serverIpEndPoint);//与服务端牵手 _threadReceive = new Thread(Receive);
_threadReceive.Start(); } private void Receive()
{
try
{
while (true)
{
Byte[] buffer = _udpClient.Receive(ref _serverIpEndPoint);
textBox1.Text = Encoding.UTF8.GetString(buffer) + _serverIpEndPoint; }
}
catch
{
_threadReceive.Abort();
} } private void Form1FormClosing(object sender, FormClosingEventArgs e)
{
_udpClient.Close();
}
}
}

服务端:

using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading; namespace WinFormP2pServer
{
public partial class Form1 : Form
{
public Form1()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
} private readonly UdpClient _udpClientServer = new UdpClient();//只允许别人用这个端口号连接我 , udp 服务端
private IPEndPoint _clientIpEndPoint = new IPEndPoint(IPAddress.Any, );// 允许任何人联系我 , 对方的连接 对象
private Thread _threadReceive;
private void Form1Load(object sender, EventArgs e)
{
_threadReceive = new Thread(Receive);
_threadReceive.Start(); } private void Receive()
{
try
{
while (true)
{
Byte[] buffer = _udpClientServer.Receive(ref _clientIpEndPoint);
textBox1.Text = Encoding.UTF8.GetString(buffer) + _clientIpEndPoint; }
}
catch
{
_threadReceive.Abort();
} } private void Form1FormClosing(object sender, FormClosingEventArgs e)
{
_udpClientServer.Close();
_threadReceive.Abort();
} private void Button1Click(object sender, EventArgs e)
{
try
{
var temp = Encoding.UTF8.GetBytes("Hello");
_udpClientServer.Send(temp, temp.Length, _clientIpEndPoint);
}
catch
{ } }
}
}

效果图:

Socket 学习(三).2  udp  穿透  服务端 与 客户端 通讯

这里其实已经实现穿透了。。。