// 客户端
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text.RegularExpressions;
namespace ClientApp
{
class ClientApp
{
[STAThread]
static void Main(string[] args)
{
MyClient myClient = new MyClient();
myClient.Run();
}
}
class MyClient
{
private string hostIP;
private string hostPort;
//private TcpClient client;
private NetworkStream stream;
private Socket client;
public MyClient()
{
InitializeComponents();
}
private void InitializeComponents()
{
Console.WriteLine( "Client is running ... " );
bool inputCorrect = false;
while( inputCorrect != true )
{
/*Console.Write("Please input the HostIP: ");
hostIP = Console.ReadLine();
Console.Write("Please input the HostPort: ");
hostPort = Console.ReadLine();
*/
hostIP = "210.22.14.6";
hostPort = "3076";
if( IsValidIPAddress(hostIP) != true || IsValidPort(hostPort) != true )
Console.WriteLine("> Error: Invalid IP or Port!");
else
inputCorrect = true;
}
}
private bool IsValidIPAddress( string strIP )
{
// Return true if strIP is in valid ipAddress format.
return Regex.IsMatch(strIP,@"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
}
private bool IsValidPort( string strPort )
{
int port;
if( Regex.IsMatch(strPort, "^[0-9]*[1-9][0-9]*$") )
{
port = Convert.ToInt32(strPort);
if( port < 65535 )
return true;
}
return false;
}
public void Run()
{
try
{
IPEndPoint ipe = new IPEndPoint( IPAddress.Parse(hostIP),Int32.Parse(hostPort));
client = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Connect " + hostIP + ":" + hostPort);
client.Connect(ipe);
Console.WriteLine("Connected Successfully.");
//stream=new NetworkStream(client); // NetworkStream
Student student = new Student(client);
student.Process();
}
catch( Exception err )
{
Console.WriteLine(err.ToString());
}
finally
{
client.Close();
}
}
}
class Student
{
private bool over;
private NetworkStream stream; //System.Net.Sockets
private StreamWriter writer;
private StreamReader reader;
private string clientCommand;
private string serverResponse;
private Socket client;
private char[] buffer;
private static string staticPath = @"c:\";
public Student(Socket client)
{
this.client = client;
stream=new NetworkStream(this.client); // NetworkStream
InitializeComponent();
}
private void InitializeComponent()
{
over = false;
writer = new StreamWriter(stream);
writer.AutoFlush=true;
reader = new StreamReader(stream);
buffer = new char[1024];
}
# region 辅助函数
private string RetCommand(string inputCommand)
{
string[] str = inputCommand.Split(' ');
return str[0].ToString();
}
private string RetTrueOutPutString(string Output)
{
int index;
index = Output.IndexOf("<OVER>");
return Output.Substring(0,index);
}
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) + "]");
while ((bytes = input.Read(buffer,0,buffer.Length)) > 0)
{
client.Send(buffer, bytes, 0);
}
input.Close();
if(client.Connected)
{
return true;
}
else
return false;
}
/// <summary>
/// 下载函数
/// </summary>
/// <param name="client">Sockets套接字</param>
/// <param name="LocalFilePath">服务器端本地的目标文件路径(包含文件名)</param>
/// <param name="isFileExists">返回该目录下是否存在该文件</param>
/// <param name="TransFeredFileSize">返回该文件的大小</param>
/// <returns>传输是否成功</returns>
private bool download(Socket client,string LocalFilePath,out long offSet,string DesPath)
{
int bytes;
//isFileExists = false;
long TransFeredFileSize = 0;
bool isException = false;
Byte[] buffer = new Byte[1024];
string FileName = LocalFilePath.Trim();
if(File.Exists(DesPath + "\\" + FileName))
{
//isFileExists = true;
//偏移量 文件存储的开始 索引
FileInfo localFile = new FileInfo(DesPath + "\\" + FileName);
offSet = TransFeredFileSize = localFile.Length;
//
localFile.Delete();
Stream st = File.Create(DesPath + "\\" + FileName);
st.Close();
///
FileStream output = new FileStream(DesPath + "\\" + FileName,FileMode.Open);
//offSet =TransFeredFileSize;
offSet = 0;
output.Seek(offSet,SeekOrigin.Begin);
try
{
byte[] byte1 = new byte[1];
byte1[0] = 2;
client.Send(byte1);
while(true)
{
bytes = client.Receive(buffer, buffer.Length, 0);
//为支持蓄传功能 从文件的大小处开始前移 52 个字节
//output.Write(buffer,TransFeredFileSize - 52,bytes);
output.Write(buffer,0,bytes);
if(bytes <=1023)
{
break;
}
}
if(client.Connected)
isException = true;
else
isException = false;
output.Close();
}
catch(Exception ex2)
{}
finally
{
if(!output.CanWrite)
output.Close();
}
}
else
{
offSet = 0;
Stream st = File.Create(DesPath + "\\" + FileName);
st.Close();
FileStream output = new FileStream(DesPath + "\\" + FileName,FileMode.Open);
try
{
byte[] byte1 = new byte[1];
byte1[0] = 2;
client.Send(byte1);
while(true)
{
bytes = client.Receive(buffer, buffer.Length, 0);
output.Write(buffer,0,bytes);
if(bytes <=1023)
{
break;
}
}
if(client.Connected)
isException = true;
else
isException = false;
output.Close();
}
catch(Exception ex3)
{}
finally
{
if(!output.CanWrite)
output.Close();
}
}
if(isException)
return true;
else
return false;
}
#endregion
void Commulation()
{
Byte[] buffer1 = new Byte[10];
client.Receive(buffer1);
Thread.Sleep(500);
if(buffer1[0].ToString() == "60")
this.upload(this.client,clientCommand.Split(' ')[1],0);
}
void Commulation1()
{
long offSet;
this.download(this.client,clientCommand.Split(' ')[1],out offSet,clientCommand.Split(' ')[2]);
}
public void Process()
{
string str = "";
string sResult = "";
bool PrintOverTag = false;
//bool isFileExists;
//long transFeredFileSize = 0;
bool FileTransferTag1 = false;
int counter = 0;
try
{
serverResponse = reader.ReadLine();
while( serverResponse != "")
{
Console.WriteLine( serverResponse );
serverResponse = reader.ReadLine();
}
while( !over )
{
counter ++ ;
reader.Read(buffer, 0, 1024);
str = new string(buffer);
if(counter !=1 && !PrintOverTag)
{
sResult = str;
int index = sResult.IndexOf("<OVER>");
if(index!=-1)
sResult = sResult.Substring(0,index);
Console.Write(sResult);
}
if(str.IndexOf("<OVER>")==-1)
continue;
else
PrintOverTag = true;
clientCommand = Console.ReadLine();
if(this.RetCommand(clientCommand)=="get")
{
writer.WriteLine(clientCommand);
this.Commulation1();
byte[] byte1 = new byte[1];
byte1[0] = 2;
client.Send(byte1);
PrintOverTag = false;
continue;
}
writer.WriteLine(clientCommand);
if(PrintOverTag)
{
PrintOverTag = false;
Console.WriteLine( reader.ReadLine() );
Console.Write("\r\n");
clientCommand = Console.ReadLine();
//writer.WriteLine(clientCommand);
string SplitStr = this.RetCommand(clientCommand);
switch(SplitStr)
{
case "dir":
case "setdir":
case "copy":
case "cd":
case "md":
case "del":
case "move":
writer.WriteLine(clientCommand);
break;
case "exit":
over = true;
break;
case "update":
writer.WriteLine(clientCommand);
this.Commulation();
//PrintOverTag = true;
break;
case "get":
writer.WriteLine(clientCommand);
this.Commulation1();
byte[] byte1 = new byte[1];
byte1[0] = 2;
client.Send(byte1);
PrintOverTag = false;
//if(isFileExists)
// Console.Write("该文件已存在,请将其删除,再进行文件传输");
break;
case "thunders":
Console.Write("HELLO 海廷::)");
break;
default:
clientCommand = "*";
break;
}
sResult = "";
}
Console.WriteLine( reader.ReadLine().Replace("<OVER>","") );
}
}
catch(Exception ex)
{
//Console.WriteLine("系统报错!" + ex.Message);
Console.WriteLine(ex.ToString());
Console.Read();
}
finally
{
writer.Close();
reader.Close();
stream.Close();
Console.Read();
}
}
}
}