c# 写的 功能强大的 FTP服务器 完全兼容 任何 FTP客户端,最兼容 IE.功能强大 防DDOS 等 .目前只提供下载.希望大家一起改善.
此服务端是我 根据FTP 抓包写成.
form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.IO;
namespace WindowsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TcpListener ftp;
Socket socket;
public static string ftpdir = "D://";
public static int sendfilebyteleng =512;
public ArrayList arrThreads = new ArrayList();
private void button1_Click(object sender, EventArgs e)
{
if (this.textBox2.Text != "")
ftpdir = this.textBox2.Text;
sendfilebyteleng = int.Parse(this.textBox3.Text);
Thread start = new Thread(new ThreadStart(starts));
start.Start();
oo = int.Parse(this.textBox4.Text);
}
private void starts()
{
ftp = new TcpListener(int.Parse(this.textBox1.Text));
try
{
ftp.Stop();
}
catch { }
try
{
ftp.Start();
}
catch { }
while (true)
{
try
{
socket = ftp.AcceptSocket();
}
catch
{
}
int ko=getiplist(((IPEndPoint)socket.RemoteEndPoint).Address.ToString());
if (ko < int.Parse(this.textBox5.Text))
{
// this.richTextBox1.BeginInvoke(new System.EventHandler(UpdateUI), ((IPEndPoint)socket.RemoteEndPoint).Address.ToString() + "以连接");
ftps boot = new ftps(socket);
boot.whowmesss += new whowmess(boot_whowmesss);
boot.iplist += new getiplist(boot_iplist);
boot.ip = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString();
this.listBox1.BeginInvoke(new System.EventHandler(UpdateUI2), ((IPEndPoint)socket.RemoteEndPoint).Address.ToString());
Thread thrd = new Thread(new ThreadStart(boot.Run));
arrThreads.Add(thrd);
thrd.Start();
}
else
{
socket.Close();
}
}
}
void boot_iplist(string e)
{
this.listBox1.BeginInvoke(new System.EventHandler(UpdateUI3), e);
}
private int getiplist(string ip)
{
int k = 0;
//for (int i = 0; i < this.listBox1.Items.Count; i++)
//{
// if (this.listBox1.FindString
// {
// k++;
// }
//}
k= this.listBox1.FindString(ip);
return k;
}
private void UpdateUI2(object o, System.EventArgs e)
{
this.listBox1.Items.Add(o.ToString());
this.label6.Text = this.listBox1.Items.Count.ToString();
}
private void UpdateUI3(object o, System.EventArgs e)
{
this.listBox1.Items.Remove(o.ToString());
this.label6.Text = this.listBox1.Items.Count.ToString();
}
private void UpdateUI(object o, System.EventArgs e)
{
this.richTextBox1.AppendText(o.ToString()+"/n");
if (richTextBox1.Lines.Length > 1000)
{
richTextBox1.Text = "";
GC.Collect();
}
}
public void Stop()
{
for (int i = 0; i < arrThreads.Count; i++)
{
Thread thrd = (Thread)arrThreads[i];
thrd.Interrupt();
}
try
{
ftp.Stop();
}
catch { }
try
{
socket.Close();
}
catch { }
arrThreads = new ArrayList();
}
static public int oo;
private void button2_Click(object sender, EventArgs e)
{
Stop();
}
private void Form1_Load(object sender, EventArgs e)
{
}
void boot_whowmesss(string e)
{
this.richTextBox1.BeginInvoke(new System.EventHandler(UpdateUI), e);
}
static public bool sendFiles(string filename, Socket sropop, int rest)
{
FileStream pStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
//ReaderWriterLock locker = new ReaderWriterLock();
byte[] buffer = new byte[Form1.sendfilebyteleng];
int number;
pStream.Seek(rest, SeekOrigin.Begin);
//lock (pStream)
// {
// pStream.Lock(rest, buffer.Length);
// locker.AcquireReaderLock(Timeout.Infinite);
Monitor.Enter(pStream);
while ((number = pStream.Read(buffer, 0, buffer.Length)) > 0)
{
// locker.ReleaseReaderLock();
// pStream.Unlock(rest, buffer.Length);
Monitor.Exit(pStream);
sropop.Send(buffer, buffer.Length, SocketFlags.None);
Thread.Sleep(oo); //45K
// rest += number;
// pStream.Lock(rest, buffer.Length);
// locker.AcquireReaderLock(Timeout.Infinite);
Monitor.Enter(pStream);
}
Monitor.Exit(pStream);
// locker.ReleaseReaderLock();
// }
// pStream.Lock(0, pStream.Length);
pStream.Close();
GC.Collect();
return true;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
using System.IO;
namespace WindowsApplication3
{
public delegate void whowmess(string e);
public delegate void getiplist(string e);
class ftps
{
public event whowmess whowmesss;
public event getiplist iplist;
Socket m_sockClient; //, m_sockServer;
Byte[] readBuf = new Byte[1];
Byte[] buffer = null;
Encoding ASCII = Encoding.ASCII;
public string ip;
private string pwd = "//";
Random counst = new Random();
opop akf = null;
System.Timers.Timer times = new System.Timers.Timer();
public ftps(Socket o)
{
m_sockClient = o;
times.Interval = 3000;
times.Elapsed += new System.Timers.ElapsedEventHandler(times_Elapsed);
}
void times_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
CLOSE();
}
private Thread vii = null;
private string user;
private string pass;
public void Run()
{
string message = "220 Luyikk FTP Service";
SendMessage(m_sockClient, message);
message = ReadMessages(m_sockClient, readBuf);
if (message.IndexOf("USER") >= 0)
{
user = getmess("USER ", message);
}else
if (message.IndexOf("user") >= 0)
{
user = getmess("user ", message);
}
else
{
message = message.Replace('/r', ' ');
message = message.Replace('/n', ':');
SendMessage(m_sockClient, "500 " + message + " command not understood");
CLOSE();
}
SendMessage(m_sockClient, "331 Password required for "+user+".");
message = ReadMessages(m_sockClient, readBuf);
if (message.IndexOf("PASS") >= 0)
{
pass = getmess("PASS ", message);
}
else
if (message.IndexOf("pass") >= 0)
{
pass = getmess("pass ", message);
}
else
{
message = message.Replace('/r', ' ');
message = message.Replace('/n', ':');
SendMessage(m_sockClient, "500 " + message + " command not understood");
CLOSE();
}
if (getuser(user, pass) == false)
{
SendMessage(m_sockClient, "530 User " + user + " cannot log in.");
CLOSE();
//m_sockClient.Close();
//GC.Collect();
//Thread.CurrentThread.Abort();
}
else
{
times.Interval = 120000;
SendMessage(m_sockClient, "230 User " + user + " logged in.");
while (true)
{
top:
message = ReadMessage(m_sockClient, readBuf);
if (message.IndexOf("/n")>0)
{
try
{
message = message.Substring(0, message.IndexOf("/r/n"));
}
catch
{
}
if (message == "opts utf8 on" || message == "OPTS UTF8 ON")
{
SendMessage(m_sockClient, "501 option not supported");
}
else if (message == "syst" || message == "SYST")
{
SendMessage(m_sockClient, "215 Luyikk server");
}
else if (message == "site help" || message == "SITE HELP")
{
SendMessage(m_sockClient, "214-The following SITE commands are recognized(* ==>'s unimplemented)./r/n CKM /r/n DIRSTYLE /r/n HELP /r/n STATS /r/n214 HELP command successful.");
}
else if (message == "help" || message == "HELP")
{
SendMessage(m_sockClient,
"214-The following commands are recognized(* ==>'s unimplemented)./r/n"
+ " ABOR /r/n"
+ " ACCT /r/n"
+ " ALLO /r/n"
+ " APPE /r/n"
+ " CDUP /r/n"
+ " CWD /r/n"
+ " DELE /r/n"
+ " FEAT /r/n"
+ " HELP /r/n"
+ " LIST /r/n"
+ " MDTM /r/n"
+ " MKD /r/n"
+ " MODE /r/n"
+ " NLST /r/n"
+ " NOOP /r/n"
+ " OPTS /r/n"
+ " PASS /r/n"
+ " PASV /r/n"
+ " PORT /r/n"
+ " PWD /r/n"
+ " QUIT /r/n"
+ " REIN /r/n"
+ " REST /r/n"
+ " RETR /r/n"
+ " RMD /r/n"
+ " RNFR /r/n"
+ " RNTO /r/n"
+ " SITE /r/n"
+ " SIZE /r/n"
+ " SMNT /r/n"
+ " STAT /r/n"
+ " STOR /r/n"
+ " STOU /r/n"
+ " STRU /r/n"
+ " SYST /r/n"
+ " TYPE /r/n"
+ " USER /r/n"
+ " XCUP /r/n"
+ " XCWD /r/n"
+ " XMKD /r/n"
+ " XPWD /r/n"
+ " XRMD /r/n"
+ "214 HELP command successful./r/n");
}
else if (message == "PWD" || message == "pwd")
{
string getpwd = pwd.Replace('//', '/');
SendMessage(m_sockClient, "257 /" "+getpwd+" /" is current directory.");
}
else if (message == "PASV" || message == "pasv")
{
Thread.Sleep(50);
SendMessage(m_sockClient, PASVx());
bool con= akf.opopstart();
if (con == false)
{
SendMessage(m_sockClient, "421 Timeout (4 seconds): closing control connection.");
goto top;
}
mes:
message = ReadMessage(m_sockClient, readBuf);
if (message.Length > 3)
{
message = message.Substring(0, message.IndexOf("/r/n"));
}
if (message == "LIST" || message == "list")
{
Thread.Sleep(10);
SendMessage(m_sockClient, "125 Data connection already open; Transfer starting.");
if (akf.varlistcmd("LIST", pwd) == true)
{
SendMessage(m_sockClient, "226 Transfer complete.");
akf.closex();
}
else
{
CLOSE();
}
}
else if (message.IndexOf("LIST") == 0)
{
Thread.Sleep(50);
try
{
SendMessage(m_sockClient, "125 Data connection already open; Transfer starting.");
string spwd = getmesscmd("LIST ", message);
spwd = spwd.Replace('/', '//');
String[] DirList = Directory.GetDirectories(Form1.ftpdir + spwd);
DirectoryInfo curDir = new DirectoryInfo(Form1.ftpdir + spwd);
if (curDir.FullName.IndexOf(Form1.ftpdir) < 0)
{
throw new Exception("NOT DIR");
}
if (akf.varlistcmd("LIST", spwd) == true)
{
SendMessage(m_sockClient, "226 Transfer complete.");
akf.closex();
}
else
{
CLOSE();
}
}
catch
{
akf.closex();
SendMessage(m_sockClient, "550 The system cannot find the file specified.");
}
}
else if (message.IndexOf("list") == 0)
{
try
{
Thread.Sleep(50);
SendMessage(m_sockClient, "125 Data connection already open; Transfer starting.");
string spwd = getmesscmd("list ", message);
spwd = spwd.Replace('/', '//');
String[] DirList = Directory.GetDirectories(Form1.ftpdir + spwd);
DirectoryInfo curDir = new DirectoryInfo(Form1.ftpdir + spwd);
if (curDir.FullName.IndexOf(Form1.ftpdir) < 0)
{
throw new Exception("NOT DIR");
}
if (akf.varlistcmd("LIST", spwd) == true)
{
SendMessage(m_sockClient, "226 Transfer complete.");
akf.closex();
}
else
{
CLOSE();
}
}
catch
{
akf.closex();
SendMessage(m_sockClient, "550 The system cannot find the file specified.");
}
}else if (message.IndexOf("SIZE") == 0)
{
Thread.Sleep(100);
message = getmesscmd("SIZE ", message).Trim(' ');
try
{
SendMessage(m_sockClient, "213 " + getfilebyte(message).ToString());
goto mes;
}
catch
{
SendMessage(m_sockClient, "550 "+message+" The system cannot find the file specified.");
goto mes;
}
}else
if (message.IndexOf("size") == 0)
{
Thread.Sleep(100);
message = getmesscmd("size ", message).Trim(' ');
try
{
SendMessage(m_sockClient, "213 " + getfilebyte(message).ToString());
goto mes;
}
catch
{
SendMessage(m_sockClient, "550 " + message + " The system cannot find the file specified.");
goto mes;
}
}
else if (message.IndexOf("RETR") == 0)
{
Thread.Sleep(20);
Retrfile("RETR ", message);
}
else if (message.IndexOf("retr") == 0)
{
Thread.Sleep(20);
Retrfile("retr ", message);
}
else if (message.IndexOf("REST") == 0)
{
Thread.Sleep(20);
try
{
message = getmesscmd("REST ", message).Trim(' ');
akf.rest = int.Parse(message);
SendMessage(m_sockClient, "350 Restarting at "+akf.rest.ToString()+".");
goto mes;
}
catch
{
SendMessage(m_sockClient, "501 Reply marker is invalid.");
goto mes;
}
}
else if (message.IndexOf("rest") == 0)
{
Thread.Sleep(20);
try
{
message = getmesscmd("rest ", message).Trim(' ');
akf.rest = int.Parse(message);
SendMessage(m_sockClient, "350 Restarting at " + akf.rest.ToString() + ".");
goto mes;
}
catch
{
SendMessage(m_sockClient, "501 Reply marker is invalid.");
goto mes;
}
}
}
else if (message == "noop" || message == "NOOP")
{
SendMessage(m_sockClient, "200 NOOP command successful.");
}
else if (message.IndexOf("TYPE") == 0 || message.IndexOf("type") == 0)
{
message = message.Remove(0, 4);
if (message.IndexOf("A") >= 0 || message.IndexOf("a") >= 0)
{
SendMessage(m_sockClient, "200 Type set to A.");
}
else
if (message.IndexOf("E") >= 0 || message.IndexOf("e") >= 0)
{
SendMessage(m_sockClient, "200 Type set to E.");
}
else
if (message.IndexOf("I") >= 0 || message.IndexOf("i") >= 0)
{
SendMessage(m_sockClient, "200 Type set to I.");
}
else
if (message.IndexOf("L") >= 0 || message.IndexOf("l") >= 0)
{
SendMessage(m_sockClient, "200 Type set to l.");
}
else
{
CLOSE();
}
}
else if (message == "QUIT" || message == "quit")
{
SendMessage(m_sockClient, "221 ");
CLOSE();
}
else if (message.IndexOf("CWD")==0)
{
Thread.Sleep(100);
try
{
string spwd = getmesscmd("CWD ", message).Trim(' ');
if (spwd.IndexOf("/ / /") > -1 && spwd.Length<6)
{
try
{
DirectoryInfo dir = new DirectoryInfo(Form1.ftpdir + pwd);
pwd = dir.Parent.FullName + "//";
pwd = pwd.Remove(pwd.IndexOf(Form1.ftpdir), Form1.ftpdir.Length);
SendMessage(m_sockClient, "250 CWD command successful.");
}
catch
{
pwd = "//";
SendMessage(m_sockClient, "250 CWD command successful.");
}
}
else
{
spwd = spwd.Replace('/', '//');
if (spwd.IndexOf("//") > -1)
{
spwd = spwd.Trim(new char[] { '//', ' ' }) + "//";
String[] DirList = Directory.GetDirectories(Form1.ftpdir + spwd);
DirectoryInfo curDir = new DirectoryInfo(Form1.ftpdir + spwd);
if (curDir.FullName.IndexOf(Form1.ftpdir) < 0)
{
throw new Exception("NOT DIR");
}
else
{
pwd = spwd.TrimStart(new char[] { '//', ' ', '//', ' ', '//' });
}
}
else
{
spwd += "//";
String[] DirList = Directory.GetDirectories(Form1.ftpdir + pwd + spwd);
DirectoryInfo curDir = new DirectoryInfo(Form1.ftpdir + pwd + spwd);
if (curDir.FullName.IndexOf(Form1.ftpdir) < 0)
{
throw new Exception("NOT DIR");
}
else
{
pwd = pwd + spwd.TrimStart(new char[] { '//', ' ', '//', ' ', '//' });
}
}
SendMessage(m_sockClient, "250 CWD command successful.");
}
}
catch
{
pwd = "//";
SendMessage(m_sockClient, "550 The system cannot find the file specified.");
}
}
else if (message.IndexOf("cwd") == 0)
{
Thread.Sleep(100);
try
{
string spwd = getmesscmd("cwd ", message).Trim(' ');
if (spwd.IndexOf("bin") > -1 || spwd.IndexOf("BIN") > -1)
{
pwd = "//";
SendMessage(m_sockClient, "250 CWD command successful.");
}
else if (spwd.IndexOf("/ / /") > -1 && spwd.Length < 6)
{
try
{
DirectoryInfo dir = new DirectoryInfo(Form1.ftpdir + pwd);
pwd = dir.Parent.FullName + "//";
pwd = pwd.Remove(pwd.IndexOf(Form1.ftpdir), Form1.ftpdir.Length );
SendMessage(m_sockClient, "250 CWD command successful.");
}
catch
{
pwd = "//";
SendMessage(m_sockClient, "250 CWD command successful.");
}
}
else
{
spwd = spwd.Replace('/', '//');
if (spwd.IndexOf("//") > -1)
{
spwd = spwd.Trim(new char[] { '//', ' ' }) + "//";
String[] DirList = Directory.GetDirectories(Form1.ftpdir + spwd);
DirectoryInfo curDir = new DirectoryInfo(Form1.ftpdir + spwd);
if (curDir.FullName.IndexOf(Form1.ftpdir) < 0)
{
throw new Exception("NOT DIR");
}
else
{
pwd = spwd.TrimStart(new char[] { '//', ' ', '//', ' ', '//' });
}
}
else
{
spwd += "//";
String[] DirList = Directory.GetDirectories(Form1.ftpdir + pwd + spwd);
DirectoryInfo curDir = new DirectoryInfo(Form1.ftpdir + pwd + spwd);
if (curDir.FullName.IndexOf(Form1.ftpdir) < 0)
{
throw new Exception("NOT DIR");
}
else
{
pwd = pwd + spwd.TrimStart(new char[] { '//', ' ', '//', ' ', '//' });
}
}
SendMessage(m_sockClient, "250 CWD command successful.");
}
}
catch
{
pwd = "//";
SendMessage(m_sockClient, "550 The system cannot find the file specified.");
}
}
else if (message.IndexOf("SIZE") == 0)
{
message = getmesscmd("SIZE ", message).Trim(' ');
try
{
SendMessage(m_sockClient, "213 " + getfilebyte(message).ToString());
}
catch
{
SendMessage(m_sockClient, "550 " + message + " The system cannot find the file specified.");
}
}
else
if (message.IndexOf("size") == 0)
{
message = getmesscmd("size ", message).Trim(' ');
try
{
SendMessage(m_sockClient, "213 " + getfilebyte(message).ToString());
}
catch
{
SendMessage(m_sockClient, "550 " + message + " The system cannot find the file specified.");
}
}
else if (message.IndexOf("REST") == 0)
{
try
{
message = getmesscmd("REST ", message).Trim(' ');
akf.rest = int.Parse(message);
SendMessage(m_sockClient, "350 Restarting at " + akf.rest.ToString() + ".");
}
catch
{
SendMessage(m_sockClient, "501 Reply marker is invalid.");
}
}
else if (message.IndexOf("rest") == 0)
{
try
{
message = getmesscmd("rest ", message).Trim(' ');
akf.rest = int.Parse(message);
SendMessage(m_sockClient, "350 Restarting at " + akf.rest.ToString() + ".");
}
catch
{
SendMessage(m_sockClient, "501 Reply marker is invalid.");
}
}
else if (message.IndexOf("RETR") == 0)
{
SendMessage(m_sockClient, "125 Data connection already open; Transfer starting.");
}
else if (message.IndexOf("rest") == 0)
{
SendMessage(m_sockClient, "125 Data connection already open; Transfer starting.");
}
else
{
SendMessage(m_sockClient, "500 " + message + ": command not understood");
}
}
else
{
break;
}
}
CLOSE();
}
CLOSE();
}
private void Retrfile(string top, string message)
{
string file = getmesscmd(top, message).Trim(' ');
try
{
FileInfo newfile = new FileInfo(Form1.ftpdir + pwd + file);
if (newfile.FullName.IndexOf(Form1.ftpdir) < 0)
{
if (whowmesss != null)
{
whowmesss(ip + "非法下载" + newfile.FullName + "/n");
}
throw new Exception("NOT DIR");
}
if (whowmesss != null)
{
whowmesss(ip + "开始下载"+newfile.FullName+"/n");
}
SendMessage(m_sockClient, "125 Data connection already open; Transfer starting.");
if (akf.sendFile(newfile.FullName) == true)
{
SendMessage(m_sockClient, "226 Transfer complete.");
}
else
{
throw new Exception("NOT DIR");
}
if (whowmesss != null)
{
whowmesss(ip + "完成下载" + newfile.FullName + "/n");
}
akf.closex();
}
catch (FileNotFoundException e)
{
if (whowmesss != null)
{
whowmesss(ip + "正在下载未知文件/n");
}
SendMessage(m_sockClient, "550 " + file + " The system cannot find the file specified.");
akf.closex();
}
catch(Exception ex)
{
akf.closex();
if (whowmesss != null)
{
whowmesss(ip + "下载文件时发生错误:/n "+ex.Message);
}
SendMessage(m_sockClient, "552 Requested file action aborted.");
CLOSE();
}
}
private long getfilebyte(string filename)
{
Thread.Sleep(100);
FileInfo file = new FileInfo(Form1.ftpdir + pwd + filename);
return file.Length;
}
private void CLOSE()
{
try
{
times.Close();
m_sockClient.Close();
//if (whowmesss != null)
//{
// whowmesss(ip + "以断开/n");
//}
if (iplist != null)
{
iplist(ip);
}
GC.Collect();
Thread.CurrentThread.Abort();
}
catch
{
GC.Collect();
}
}
private string PASVx()
{
IPHostEntry ipc = Dns.Resolve(Environment.MachineName);
if (ipc.AddressList.Length > 0)
{
string ip = ipc.AddressList[0].ToString().Replace('.', ',');
int prot = counst.Next(1400, 3600);
int protbyte = prot / 256;
int protc = prot - (protbyte * 256);
akf = new opop(prot);
//if (vii != null)
//{
// vii.Abort();
//}
//vii=new Thread(new ThreadStart(akf.opopstart));
//vii.Start();
return "227 Entering Passive Mode (" + ip + "," + protbyte + "," + protc + ").";
}
return "";
}
private string getmess(string head, string message)
{
try
{
int tp= message.IndexOf(head);
string mess= message.Remove(tp, head.Length);
return mess.Substring(0, mess.IndexOf("/r"));
}
catch
{
return message;
}
}
private string getmesscmd(string head, string message)
{
try
{
int tp = message.IndexOf(head);
string mess = message.Remove(tp, head.Length);
return mess;
}
catch
{
return message;
}
}
bool getuser(string user,string pass)
{
if (user != "luyikk")
{
return false;
}
else if (pass != "123123")
{
return false;
}
else
{
return true;
}
// return true;
}
string ReadMessages(Socket sock, byte[] buf)
{
int iBytes = 0;
ArrayList x = new ArrayList();
byte[] mmx = null;
while (true)
{
times.Start();
try
{
iBytes = sock.Receive(buf, 1, 0);
}
catch
{
CLOSE();
}
times.Stop();
x.Add(buf[0]);
if (buf[0] == 10)
{
break;
}
else if (x.Count > 50)
{
break;
}
}
mmx = new byte[x.Count];
for (int i = 0; i < mmx.Length; i++)
{
mmx[i] = (byte)x[i];
}
return Encoding.Default.GetString(mmx);
}
string ReadMessage(Socket sock, byte[] buf)
{
int iBytes = 0;
ArrayList x = new ArrayList();
byte[] mmx = null;
while (true)
{
times.Start();
try
{
iBytes = sock.Receive(buf, 1, 0);
}
catch
{
CLOSE();
}
times.Stop();
x.Add(buf[0]);
if (buf[0] == 10)
{
break;
}
else if(x.Count>1024)
{
break;
}
}
mmx = new byte[x.Count];
for (int i = 0; i < mmx.Length; i++)
{
mmx[i] = (byte)x[i];
}
return Encoding.Default.GetString(mmx);
}
//string ReadMessage(Socket sock, byte[] buf)
//{
// int iBytes = 0;
// string strmess = "";
// while (true)
// {
// times.Start();
// try
// {
// iBytes = sock.Receive(buf, 1, 0);
// }
// catch
// {
// CLOSE();
// }
// times.Stop();
// //string vo = Encoding.GetEncoding("gb2312").GetString(buf);
// string vo = Encoding.Default.GetString(buf);
// strmess += vo;
// if (strmess.IndexOf("/n") > 0)
// {
// byte[] kass = Encoding.Default.GetBytes(strmess);
// strmess = Encoding.Default.GetString(kass);
// return strmess;
// }
// else if (strmess.Length > 50)
// {
// return strmess;
// }
// }
//}
void SendMessage(Socket sock, string Message)
{
string strMessage = Message + "/r/n";
buffer = new Byte[strMessage.Length + 1];
int len = ASCII.GetBytes(strMessage.ToCharArray(),
0, strMessage.Length, buffer, 0);
try
{
times.Start();
sock.Send(buffer, len, 0);
times.Stop();
}
catch { GC.Collect(); }
}
}
}
opop.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
using System.IO;
namespace WindowsApplication3
{
public class opop
{
TcpListener opops = null;
Socket sropop;
public int rest = 0;
System.Timers.Timer times = new System.Timers.Timer();
byte[] buffer = null;
public opop(int port)
{
opops = new TcpListener(port);
times.Interval = 4000;
times.Elapsed += new System.Timers.ElapsedEventHandler(times_Elapsed);
}
void times_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
closex();
}
public bool opopstart()
{
try
{
opops.Start();
times.Start();
sropop = opops.AcceptSocket();
times.Stop();
return true;
}
catch
{
GC.Collect();
return false;
}
}
public bool varlistcmd(string cmd,string dir)
{
if (dir == "")
{
SendMessage(getdirlist("//"));
return true;
}
else
{
SendMessage(getdirlist(dir));
return true;
}
return false;
}
private string getdirlist(string dir)
{
if (dir == "//")
{
String[] DirList = Directory.GetDirectories(Form1.ftpdir);
String szDirList = "";
DirectoryInfo curDir = new DirectoryInfo(Form1.ftpdir);
FileInfo[] szFileListArray = curDir.GetFiles();
String szFileList = "";
for (int i = 0; i < DirList.Length; i++)
{
Thread.Sleep(10);
DirectoryInfo tmp = new DirectoryInfo(DirList[i]);
szDirList += tmp.CreationTime.ToString("MM-dd-yy");
szDirList += " ";
szDirList += tmp.CreationTime.ToString("hh:mm");
if (tmp.CreationTime.Hour > 12)
{
szDirList += "PM";
}
else
{
szDirList += "AM";
}
szDirList += " ";
szDirList += "<DIR>";
szDirList += " ";
szDirList += tmp.Name;
szDirList += "/r/n";
}
// Now Files
for (int i = 0; i < szFileListArray.Length; i++)
{
Thread.Sleep(10);
szFileList += szFileListArray[i].CreationTime.ToString("MM-dd-yy");
szFileList += " ";
szFileList += szFileListArray[i].CreationTime.ToString("hh:mm");
if (szFileListArray[i].CreationTime.Hour > 12)
{
szFileList += "PM";
}
else
{
szFileList += "AM";
}
szFileList += " ";
szFileList += szFileListArray[i].Length.ToString();
szFileList += " ";
szFileList += szFileListArray[i].Name;
szFileList += "/r/n";
}
szDirList += szFileList;
return szDirList;
}
else
{
String[] DirList = Directory.GetDirectories(Form1.ftpdir+dir);
String szDirList = "";
DirectoryInfo curDir = new DirectoryInfo(Form1.ftpdir+dir);
FileInfo[] szFileListArray = curDir.GetFiles();
String szFileList = "";
for (int i = 0; i < DirList.Length; i++)
{
Thread.Sleep(10);
DirectoryInfo tmp = new DirectoryInfo(DirList[i]);
szDirList += tmp.CreationTime.ToString("MM-dd-yy");
szDirList += " ";
szDirList += tmp.CreationTime.ToString("hh:mm");
if (tmp.CreationTime.Hour > 12)
{
szDirList += "PM";
}
else
{
szDirList += "AM";
}
szDirList += " ";
szDirList += "<DIR>";
szDirList += " ";
szDirList += tmp.Name;
szDirList += "/r/n";
}
// Now Files
for (int i = 0; i < szFileListArray.Length; i++)
{
Thread.Sleep(10);
szFileList += szFileListArray[i].CreationTime.ToString("MM-dd-yy");
szFileList += " ";
szFileList += szFileListArray[i].CreationTime.ToString("hh:mm");
if (szFileListArray[i].CreationTime.Hour > 12)
{
szFileList += "PM";
}
else
{
szFileList += "AM";
}
szFileList += " ";
szFileList += szFileListArray[i].Length.ToString();
szFileList += " ";
szFileList += szFileListArray[i].Name;
szFileList += "/r/n";
}
szDirList += szFileList;
return szDirList;
}
}
public void closex()
{
opops.Stop();
if (sropop != null)
{
sropop.Close();
}
// Thread.CurrentThread.Abort();
GC.Collect();
}
public bool sendFile(string filename)
{
// bool a = Form1.sendFiles(filename, sropop, rest);
bool a = sendFile(filename, sropop);
return a;
}
public bool sendFile(string filename, Socket sropop)
{
FileStream pStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
//BinaryReader br = new BinaryReader(pStream);
//while (br.PeekChar() > -1)
//{
// this.sropop.Send(br.ReadBytes(Form1.sendfilebyteleng));
//}
//br.Close();
//pStream.Close();
//---------------------------------------------------------------
//NetworkStream stream = new NetworkStream(sropop);
//byte[] buffer = new byte[Form1.sendfilebyteleng];
//int number;
//pStream.Seek(rest, SeekOrigin.Begin);
//while ((number = pStream.Read(buffer, 0, buffer.Length)) > 0)
//{
// stream.Write(buffer, 0, number);
// // stream.Flush();
//}
//pStream.Close();
//stream.Close();
//---------------------------------------------------------------------------------------
byte[] buffer = new byte[Form1.sendfilebyteleng];
pStream.Seek(rest, SeekOrigin.Begin);
pStream.Lock(rest, rest + Form1.sendfilebyteleng);
NBLI:
int number = 0;
try
{
number = pStream.Read(buffer, 0, buffer.Length);
}
catch
{
goto NBLI;
}
while (number > 0)
{
pStream.Unlock(rest, rest + Form1.sendfilebyteleng);
this.sropop.Send(buffer, buffer.Length, SocketFlags.None);
Thread.Sleep(Form1.oo);
rest += number;
pStream.Lock(rest, rest + Form1.sendfilebyteleng);
BLI:
try
{
number = pStream.Read(buffer, 0, buffer.Length);
}
catch
{
goto BLI;
}
}
pStream.Unlock(rest, rest + Form1.sendfilebyteleng);
pStream.Close();
GC.Collect();
return true;
//--------------------------------------------------------------------------
//int zli = 0;
//while (true)
//{
// byte[] buffer = getfilebyte(filename, rest, Form1.sendfilebyteleng, ref zli);
// if (zli <= 0)
// {
// break;
// }
// rest += zli;
// this.sropop.Send(buffer, buffer.Length, SocketFlags.None);
//}
//GC.Collect();
//return true;
}
private byte[] getfilebyte(string filename, int start, int count, ref int size)
{
FileStream pStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[count];
pStream.Seek(start, SeekOrigin.Begin);
size = pStream.Read(buffer, 0, buffer.Length);
return buffer;
}
void SendMessage(string Message)
{
string strMessage = Message + "/r/n";
buffer = Encoding.Default.GetBytes(Message);
try
{
times.Start();
sropop.Send(buffer, buffer.Length, 0);
times.Stop();
}
catch { GC.Collect(); }
}
}
}
Form1.Designer.cs
namespace WindowsApplication3
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.performanceCounter1 = new System.Diagnostics.PerformanceCounter();
this.textBox1 = new System.Windows.Forms.TextBox();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.textBox4 = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.listBox1 = new System.Windows.Forms.ListBox();
this.textBox5 = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(297, 5);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "START";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// performanceCounter1
//
this.performanceCounter1.CategoryName = "Network Interface";
this.performanceCounter1.CounterName = "Bytes Total/sec";
this.performanceCounter1.InstanceName = "Realtek RTL8139 Family PCI Fast Ethernet NIC - 数据包计划程序微型端口";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(57, 6);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 21);
this.textBox1.TabIndex = 1;
this.textBox1.Text = "21";
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(-1, 80);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(381, 138);
this.richTextBox1.TabIndex = 2;
this.richTextBox1.Text = "";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(57, 30);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(100, 21);
this.textBox2.TabIndex = 3;
this.textBox2.Text = "E://bak1//";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(21, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(29, 12);
this.label1.TabIndex = 4;
this.label1.Text = "PORT";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(21, 33);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(23, 12);
this.label2.TabIndex = 5;
this.label2.Text = "DIR";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(21, 61);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(29, 12);
this.label3.TabIndex = 6;
this.label3.Text = "size";
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(56, 57);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(100, 21);
this.textBox3.TabIndex = 7;
this.textBox3.Text = "5120";
//
// textBox4
//
this.textBox4.Location = new System.Drawing.Point(227, 5);
this.textBox4.Name = "textBox4";
this.textBox4.Size = new System.Drawing.Size(45, 21);
this.textBox4.TabIndex = 8;
this.textBox4.Text = "50";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(162, 8);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(29, 12);
this.label4.TabIndex = 9;
this.label4.Text = "速度";
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.ItemHeight = 12;
this.listBox1.Location = new System.Drawing.Point(386, 6);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(132, 208);
this.listBox1.TabIndex = 10;
//
// textBox5
//
this.textBox5.Location = new System.Drawing.Point(227, 60);
this.textBox5.Name = "textBox5";
this.textBox5.Size = new System.Drawing.Size(45, 21);
this.textBox5.TabIndex = 11;
this.textBox5.Text = "3";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(162, 65);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(65, 12);
this.label5.TabIndex = 12;
this.label5.Text = "每ip连接数";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(341, 63);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(11, 12);
this.label6.TabIndex = 13;
this.label6.Text = "0";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(518, 216);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.textBox5);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.label4);
this.Controls.Add(this.textBox4);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Diagnostics.PerformanceCounter performanceCounter1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.TextBox textBox4;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.TextBox textBox5;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
}
}
希望大家喜欢.
有问题可以M我