嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 1 元微信扫码支付:1 元
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
C#内网穿透源代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
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 PeerToPeer
{
public partial class FrmPeer : Form
{
public FrmPeer()
{
InitializeComponent();
}
Stream stream = null;
private void btn_Connention_Click(object sender, EventArgs e)
{
Task.Run(new Action(() => { Connection(); }));
}
private void Connection()
{
string localEndPoint;
int port;
IPEndPoint iPEndPoint;
string ip;
using (var tcpClient = new TcpClient())
{
//tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
tcpClient.Connect("外网IP", 3721);
var socket = tcpClient.Client;
localEndPoint = socket.LocalEndPoint.ToString();
var hostname = localEndPoint.Split(':')[0];
port = int.Parse(localEndPoint.Split(':')[1]);
PushMsg("本地ip:{hostname}本地端口{port}!\r\n");
iPEndPoint = new IPEndPoint(IPAddress.Parse(hostname), port);
PushMsg("成功链接服务器!\r\n");
var readerStream = new StreamReader(tcpClient.GetStream());
ip = readerStream.ReadLine();
PushMsg("成功获取对方ip!{ip}\r\n");
tcpClient.Client.Shutdown(SocketShutdown.Both);
tcpClient.Close();
tcpClient.Dispose();
}
var tcpClient2 = new TcpClient();
tcpClient2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
tcpClient2.Client.Bind(iPEndPoint);
PushMsg("开始链接对方!{ip}\r\n");
//for (int i = 0; i < 50; i )
//{
while (true)
{
try
{
var yp = int.Parse(ip.Split(':')[1]);
tcpClient2.Connect(ip.Split(':')[0], yp);
PushMsg("链接成功!{ip}\r\n");
this.BeginInvoke(new Action(() =>
{
btn_Send.Enabled = true;
}));
break;
}
catch (Exception ex)
{
PushMsg(ex.Message "\r\n");
}
}
//}
Task.Run(() =>
{
this.stream = tcpClient2.GetStream();
PushMsg("开始监听接收信息!\r\n");
while (true)
{
try
{
var bytedd = new byte[tcpClient2.Client.ReceiveBufferSize];
int count = stream.Read(bytedd, 0, bytedd.Length);
var result = Encoding.UTF8.GetString(bytedd, 0, count);
PushMsg("接收到消息:{result}\r\n");
}
catch (Exception ex)
{
PushMsg("接收错误{ex.Message}\r\n");
break;
}
}
});
}
private void btn_Send_Click(object sender, EventArgs e)
{
if (this.stream != null)
{
var data = Encoding.UTF8.GetBytes(rtb_Msg.Text);
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
private void PushMsg(string Msg)
{
this.BeginInvoke(new Action(() =>
{
rtb_Msg.AppendText(Msg);
}));
}
}
}