第一页(服务端) :远程资源管理器 c#应用源代码,SERVICE + CLIENT 模式 可实现远程文件管理,下载功能

这个代码是我早些时候写出来的,虽然功能完备,但代码略显稚嫩,发现有网友需要,就把他发出来了。

// 服务端
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections;
class ServerApp
{
public static void Main()
{
   Server server=new Server();
   server.Start();
}
}
class Server
{

private IPAddress ip;
private int port;
private TcpListener listener;
private Socket client;
private RequestController processor;
private Thread processingThread;
public static int UID;

public Server()
{
   InitializeComponents();
}
private void InitializeComponents()
{
   port = 44444;                                                      // 端口
   ip = Dns.Resolve(Dns.GetHostName()).AddressList[0];                // ?得当前机器ip
  
   listener = new TcpListener(ip,port);
   listener.Start();                                                  // ?始?听
   Console.WriteLine("Server " + ip.ToString() + " : " + port.ToString() + " Startup.");
   Console.Write( "Listening..." );
}
public void Start()
{
   try
   {
    while(true)                                
    {
     client = listener.AcceptSocket();       //接收客?端?接
     processor = new RequestController(client);        
     processingThread = new Thread(new ThreadStart(processor.Process));   //服?器将将生成一个新的?程来?理客?端?求
     processingThread.Start();
    }
   }
   catch(Exception ex)
   {
    Console.WriteLine(ex.ToString());
   }
   finally
   {
    listener.Stop();
   }
}
}

public class RequestController                //?理客?端?求的?
{
private bool quitRequested;    
private string welcomeMessage;
private NetworkStream stream;   //System.Net.Sockets
private StreamWriter writer;
private StreamReader reader;
private Socket client;
private string clientCommand;
private bool isSuccess;
private ArrayList alResult;
public string StaticPath
{
   get{return staticPath;}
   set{staticPath = value;}
}
private string staticPath =   @"d:\";//当前会话的静态服务器Path
public RequestController(Socket client)
{
   this.client=client;
   InitializeComponent();
}
public RequestController(string path)
{
   this.StaticPath = path;
}
private void InitializeComponent()   //初始化
{
   quitRequested = false;
   welcomeMessage="欢迎来到 THUNDERS 的远程控制中心\r\n";
   stream=new NetworkStream(client);   // NetworkStream
   writer=new StreamWriter(stream);    // StreamWriter
   writer.AutoFlush = true;
   reader=new StreamReader(stream);    // StreamReader
}
# region 辅助函数
private string RetBlank(int BlankNum)
{
   string sBlank = "";
   for(int i=0;i<BlankNum;i++)
   {
    sBlank += " ";
   }
   return sBlank;
}
private string RetalResult(ArrayList _alResult)
{
   string _sResult = "";
   for(int i=0;i<_alResult.Count;i++)
   {
    _sResult += _alResult[i].ToString() + "\r\n";
   }
   _sResult += "<OVER>";
   return _sResult;
}
private string RetCommand(string inputCommand)
{
   if(inputCommand !=null)
   {
    string[] str = inputCommand.Split(' ');
   
    return str[0].ToString();
   }
   else
    return "";
}
#endregion
public void Process()
{
   try
   {
    writer.WriteLine(welcomeMessage);   //往NetworkStream中写?迎信息
    Console.Write("\r\n用户" + Server.UID++ + " 于   " + DateTime.Now.ToString() + "登陆至服务器" );
    while(!quitRequested)               //当?求未被?止
    {
     writer.Write("<OVER>");
     clientCommand=reader.ReadLine();   //?取客?端?求(命令)
     string commStr = this.RetCommand(clientCommand);
     if(clientCommand == "")
      continue;
     switch(commStr)
     {
      case "dir":
      
      case "copy":      
     
      case "del":
     
      case "cd":      
      
      case "setdir":
     
      
      case "md":
      
      case "move":
      

      case "get":
      case "update":
       DirAccess da1= new DirAccess(this);
       this.alResult = da1.dirAccess(client,clientCommand,out isSuccess);
       writer.WriteLine(this.RetalResult(this.alResult));
       break;
    
      
      case "?":
      case "help":
      case "/help":
       writer.WriteLine("请输入指定的命令:" +
        "dir / copy / del / cd / setdir / update /get"   +
        "\r\n copy格式: 目录拷贝: copy g:\\001 c:\\001   \r\n copy格式: 文件拷贝: copy 001.txt g:\\001 \r\n   (目录为全名称,文件为半名称)\r\n<OVER>" );
       break;
      case "exit":
       quitRequested=true;
       break;
    
      default:                       // 服?器只提供"G"和"Q"命令
       writer.WriteLine("Supported Command: A, G, Q.");
       break;
     }
     Console.Write("\r\n命令操作:" + clientCommand+"\r\n");
    }
    Console.Write("\r\n用户" + Server.UID + " 于   " + DateTime.Now.ToString() + "退出服务器" );
    Server.UID--;
   }
   catch(Exception ex)
   {
    Console.WriteLine("####系统报错!    + " + ex.Message);
   }
   finally                                   
   {
    writer.Close();                      
    reader.Close();                      
    stream.Close();                     
    client.Close();                       
   }
}
public class DirAccess
{
   RequestController rc1;
   private System.IO.DirectoryInfo directoryInfo;
   public DirAccess(RequestController rc)
   {
    this.rc1 = rc;
   }
   private int RetCommandTag(string sCommand)
   {
    int CommandTag = -1;//0 为 DIR 1 为 copy 2 为 del
    if(sCommand.IndexOf("dir")!=-1)
     CommandTag = 0;
    if(sCommand.IndexOf("copy")!=-1)
     CommandTag = 1;
    if(sCommand.IndexOf("del")!=-1)
     CommandTag = 2;
    if(sCommand.IndexOf("cd")!=-1)
     CommandTag = 3;
    if(sCommand.IndexOf("setdir")!=-1)
     CommandTag = 4;
    if(sCommand.IndexOf("update")!=-1)
     CommandTag = 5;
    if(sCommand.IndexOf("get")!=-1)
     CommandTag = 6;
    if(sCommand.IndexOf("move")!=-1)
     CommandTag = 7;
    if(sCommand.IndexOf("md")!=-1)
     CommandTag = 8;
    return CommandTag;

   }
   private ArrayList convertArrayToArrayList(string[] arrStr)
   {
    ArrayList al = new ArrayList();
    for(int i=0;i< arrStr.Length;i++)
    {
     al.Add(arrStr[i]);
    }
    return al;
   }
  
   private ArrayList RetPathInfo(string path)
   {
    //DirectoryInfo di = new DirectoryInfo(@"c:\MyDir");
    DirectoryInfo dir;
    ArrayList alDir = new ArrayList();
    dir = new DirectoryInfo(path);
    for(int i=0;i<dir.GetDirectories().Length;i++)
    {
     alDir.Add("<DIR> " + dir.GetDirectories()[i].LastWriteTime.ToString("yy-MM-dd   HH:MM:ss") + "     " + dir.GetDirectories()[i].Name);
    }
    return alDir;
   }
   private ArrayList RetFileInfo(string path)
   {
    DirectoryInfo dir;
    ArrayList alDir = new ArrayList();
    dir = new DirectoryInfo(path);
    for(int i=0;i<dir.GetFiles().Length;i++)
    {
     alDir.Add("       "+ dir.GetFiles()[i].LastWriteTime.ToString("yy-MM-dd   HH:MM:ss") + "     " + dir.GetFiles()[i].Name );
    }
    return alDir;
   }
   private bool CopyDir(string toPath,string FromPath)
   {
    DirectoryInfo dir2 = new DirectoryInfo(toPath);
    if(!dir2.Exists)
     dir2.Create();
    DirectoryInfo dir1;
    dir1 = new DirectoryInfo(FromPath);
    try
    {
     this.CopyDir1(dir1,toPath,FromPath);
    }
    catch(IOException ex1)
    {
     return false;
    }
    return true;

  
   }
   private void CopyDir1(DirectoryInfo dir1,string toPath,string FromPath)
   {
    //string[] ArrayFiles = dir1.GetFiles();
    //string[] ArrayDirs = dir1.GetDirectories();
    if(dir1.GetFiles().Length>0)
    {
     for(int i = 0;i<dir1.GetFiles().Length;i++)
     {
      File.Copy(FromPath + "\\" + dir1.GetFiles()[i].Name,toPath + "\\" + dir1.GetFiles()[i].Name,true);
     }
    }
    if(dir1.GetDirectories().Length>0)
    {
     for(int j = 0;j<dir1.GetDirectories().Length;j++)
     {
      DirectoryInfo dir2 = new DirectoryInfo(toPath + "\\" + dir1.GetDirectories()[j].Name);
      dir2.Create();
      FromPath   = FromPath + "\\" + dir1.GetDirectories()[j].Name;
      this.CopyDir1(dir1.GetDirectories()[j],toPath + "\\" + dir1.GetDirectories()[j].Name,FromPath);
     }
    }
   }
   private string retFileName(string FilePath)
   {
    //c:\aa\bbf.txt
    int index;
    index = FilePath.LastIndexOf("\\");
    return FilePath.Substring(index + 1);
   }
  

   private bool upload(Socket client,string LocalFilePath,long offset)
   {
    int bytes;
    Byte[] buffer = new Byte[1024];
    //long offset;//文件的开始位置
    FileStream input = new FileStream( LocalFilePath,FileMode.Open);
    if(offset != 0)
    {
     input.Seek(offset,SeekOrigin.Begin);
    }
    //Console.Write("Uploading ....File [" + this.retFileName(LocalFilePath) + "]");
    Thread.Sleep(500);
    while ((bytes = input.Read(buffer,0,buffer.Length)) > 0)
    {
     client.Send(buffer, bytes, 0);

    }
    input.Close();
    Byte[] buffer1 = new Byte[10];
    client.Receive(buffer1);
    if(client.Connected)
    {
    
     return true;
    }
    else
     return false;

   }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值