这篇文章介绍了C#实现同步模式下的端口映射程序,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
今天打算写一个FtpServer玩一下的,需要看看ftp软件常用命令形式(完整实现所有ftp命令太麻烦),最开始打算通过抓包看cuteftp是如何访问ftpserver的,但要把其中的命令保存下来还得一条条复制,太麻烦,便通过proxy模式写了一个代理程序,来获取其交互的命令,写了一个简单的同步模式下的端口映射程序后,发现比常用的异步proxy要简单的多,便把这段代码贴出来,以备日后查询:
class Program
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, 8000));
listener.Start();
while (true)
{
var client = listener.AcceptTcpClient();
Console.WriteLine("connected");
var proxy = new TcpClient();
Console.WriteLine("remote connected");
proxy.Connect(new IPEndPoint(IPAddress.Loopback, 21));
new SyncProxy("client->remote",proxy.GetStream(), client.GetStream());
new SyncProxy("remote->client",client.GetStream(), proxy.GetStream());
}
}
}
class SyncProxy
{
NetworkStream read;
NetworkStream write;
string name;
public SyncProxy(string name, NetworkStream read,NetworkStream write)
{
this.name = name;
this.read = read;
this.write = write;
System.Threading.ThreadPool.QueueUserWorkItem(PipeStream);
}
void PipeStream(object state)
{
byte[] buffer = new byte[1500];
int count = 0;
while (true)
{
try
{
count = read.Read(buffer, 0, buffer.Length);
}
catch (Exception)
{
count = 0;
}
if (count == 0)
{
Console.WriteLine(name+" closed");
write.Close();
break;
}
Console.Write(name + ": "+ Encoding.Default.GetString(buffer, 0, count));
write.Write(buffer, 0, count);
}
}
}
通过它获取到的cuteFtp交互命令如下:
connected
remote connected
client->remote: 220 Serv-U FTP Server v6.0 for WinSock ready...
remote->client: USER 1
client->remote: 331 User name okay, need password.
remote->client: PASS 1
client->remote: 230 User logged in, proceed.
remote->client: PWD
client->remote: 257 "/" is current directory.
remote->client: FEAT
client->remote: 211-Extension supported
client->remote: CLNT
MDTM
MDTM YYYYMMDDHHMMSS[+-TZ];filename
SIZE
SITE PSWD;EXEC;SET;INDEX;ZONE;CHMOD;MSG
REST STREAM
XCRC filename;start;end
MODE Z
211 End
remote->client: REST 0
client->remote: 350 Restarting at 0. Send STORE or RETRIEVE.
remote->client: PASV
client->remote: 227 Entering Passive Mode (127,0,0,1,29,18)
remote->client: LIST
client->remote: 150 Opening ASCII mode data connection for /bin/ls.
client->remote: 226 Transfer complete.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
本文标题为:C#实现同步模式下的端口映射程序
基础教程推荐
- 一个读写csv文件的C#类 2022-11-06
- C#控制台实现飞行棋小游戏 2023-04-22
- C# windows语音识别与朗读实例 2023-04-27
- winform把Office转成PDF文件 2023-06-14
- C#类和结构详解 2023-05-30
- C# List实现行转列的通用方案 2022-11-02
- C# 调用WebService的方法 2023-03-09
- unity实现动态排行榜 2023-04-27
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- ZooKeeper的安装及部署教程 2023-01-22