if(args.Length != 0) app.CreateWait(Convert.ToInt16(args[0])); else app.CreateWait(); // // TODO: 在此处添加代码以启动应用程序 // } /// <summary> /// 构造 /// </summary> public TUploadServer() { //Socket Packet Array aSock = new TSocketPacket[MAX_CONNECT]; for(int i = 0; i< MAX_CONNECT; i++) aSock[i] = new TSocketPacket(); // byte process m_byte = new EIIByte(); nSocketNum = 0; bSend = new byte[ONCE_COUNT]; m_ascn = new ASCIIEncoding(); pfnWorkerCallBack = new AsyncCallback(OnDataReceived); proOnAccept = new AsyncCallback(OnAccept); bCheck = new Byte[2]; int pos = 0; m_byte.SetWord(bCheck,CMD_S_CHECK,ref pos);
} /// <summary> /// 创建等待连接 /// </summary> public void CreateWait(int port) { int nCount = 0;
IPAddress ip = Dns.GetHostByName(Dns.GetHostName()).AddressList[0]; // IPAddress ipAddress = IPAddress.Parse(IP); IPEndPoint ipe = new IPEndPoint(ip,port); sWait = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sWait.Bind(ipe); sWait.Listen(MAX_CONNECT); sWait.BeginAccept(proOnAccept,sWait); Console.WriteLine("The server is running at port {0}...",port); Console.WriteLine("The local End point is :" + ip.ToString() ); Console.WriteLine("Waiting for a connection.....");
3, client ////////////// using System; using System.Net.Sockets; using System.Net; using System.IO; using System.Text;using EII.Base; namespace Twindow { public enum UploadException { OPEN_FILE_FAILED = -9, CONNECT_FAILED , OTHER , OK = 0 } /// <summary> /// UpLoad 的摘要说明。 /// </summary> public class UpLoad { private const int PORT = 5656; //upload port private const int ONCE_COUNT= 1024; //once count byte private const string IP = "172.16.36.77"; private AsyncCallback proSend = null; private IAsyncResult m_asynResult; public AsyncCallback pfnCallBack ;
private Socket m_Socket; private ASCIIEncoding m_asen; private EIIByte m_byte; private int m_nPut = 0; /// <summary> /// SocketPacket /// </summary> public class CSocketPacket { public System.Net.Sockets.Socket thisSocket; public byte[] dataBuffer = new byte[1]; } /// <summary> /// 构造 /// </summary> public UpLoad() { proSend = new AsyncCallback(OnSend); m_nPut = 0; m_asen=new ASCIIEncoding(); m_byte = new EIIByte(ONCE_COUNT); } /// <summary> /// 连接 /// </summary> public bool Connect() { return Connect(IP); } /// <summary> /// 连接到指定的IP /// </summary> /// <param name="sIP"></param> public bool Connect(string sIP) { try { //create the socket instance... m_Socket = new Socket (AddressFamily.InterNetwork,SocketType.Stream ,ProtocolType.Tcp ); // get the remote IP address... IPAddress ip = IPAddress.Parse (sIP); //create the end point IPEndPoint ipEnd = new IPEndPoint (ip.Address,PORT); //connect to the remote host... m_Socket.Connect ( ipEnd ); //watch for data ( asynchronously )... WaitForData(); return true; } catch(SocketException se) { Console.WriteLine (se.Message ); return false; }
} /// <summary> /// 等待接受数据 /// </summary> public void WaitForData() { try { if ( pfnCallBack == null ) { pfnCallBack = new AsyncCallback (OnDataReceived); } CSocketPacket theSocPkt = new CSocketPacket (); theSocPkt.thisSocket = m_Socket; // now start to listen for any data... m_asynResult = m_Socket.BeginReceive (theSocPkt.dataBuffer ,0,theSocPkt.dataBuffer.Length ,SocketFlags.None,pfnCallBack,theSocPkt); } catch(SocketException se) { Console.WriteLine (se.Message ); } } /// <summary> /// 接受数据 /// </summary> /// <param name="asyn"></param> public void OnDataReceived(IAsyncResult asyn) { m_nPut = 0; //Receive: CMD(WORD = 0x0302)+reday status(BYTE 1= OK,2 = FAIL) try { CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ; //end receive... int iRx = theSockId.thisSocket.EndReceive (asyn); if (iRx != 3) m_nPut = 2; else { m_byte.SetBuffer(theSockId.dataBuffer); int pos = 0; if((0x0302 != m_byte.GetWord(ref pos ) || (1 != m_byte.GetByte(1,ref pos)[0]))) m_nPut = 2; else m_nPut = 1; } //BH txtDataRx.Text = txtDataRx.Text + szData; WaitForData(); } catch (ObjectDisposedException ) { System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n"); } catch(SocketException se) { Console.WriteLine (se.Message ); } } /// <summary> /// 上传文件 /// </summary> /// <param name="filename">要上传的文件名</param> public UploadException SendFile(string filename,string targetname) { //send : CMD(WORD = 0x0301)+filename's length(WORD)+filename(target)+size(DWORD)+times(WORD), //Receive: CMD(WORD = 0x0302)+reday status(BYTE 1= OK,2 = FAIL) if(!m_Socket.Connected ) return UploadException.CONNECT_FAILED; //return value UploadException re = UploadException.OK; //file FileStream file = null; //file size int size ; //Upload times int times ; int nTimes = 0;
try // try to open the file { file = File.OpenRead(filename); size = (int)file.Length; times = size/(ONCE_COUNT -2); m_byte.Reset(); int nFileNameLength = m_asen.GetByteCount(targetname); int pos = 0; //put data position m_byte.SetWord(0x0302,ref pos); m_byte.SetWord((short)nFileNameLength,ref pos); m_byte.SetByte(m_asen.GetBytes(targetname),ref pos); m_byte.SetDword(size,ref pos); m_byte.SetWord((short)times,ref pos); byte[] bSend = m_byte.GetBuffer(); // m_Socket.BeginSend(bSend,0,bSend.Length,SocketFlags.None,proSend,m_Socket);//Send(bSend); //等待回应 while(m_nPut == 0 && nTimes < 100) { // if( 0 != m_Socket.Receive(bSend)) // m_nPut = 2; System.Threading.Thread.Sleep(200) ; nTimes ++; } if(m_nPut == 2) return UploadException.OTHER; //组织发送包 for(int i =0; i< times; i++) { pos = 0; m_byte.SetWord(bSend,0x0303,ref pos); //cmd int n = file.Read(bSend,i*(ONCE_COUNT -2 ) + 2,ONCE_COUNT -2 ); m_Socket.Send(bSend,n + 2, SocketFlags.None ); // m_Socket.BeginSend(bSend,0,n,SocketFlags.None,proSend,m_Socket); } } catch(SocketException) // 访问 Socket 时发生操作系统错误。 { re = UploadException.CONNECT_FAILED; } catch(ObjectDisposedException) // Socket 已关闭。 { re = UploadException.CONNECT_FAILED;
namespace EII.Base
{
/// <summary>
/// EIIByte 的摘要说明。
/// </summary>
public class EIIByte
{
protected byte[] m_byte;
protected int m_nSize; /// <summary>
/// 用缓冲区长度构造
/// </summary>
/// <param name="nSize"></param>
public EIIByte(int nSize)
{
m_byte = new byte[nSize];
m_nSize= nSize; //
// TODO: 在此处添加构造函数逻辑
//
} /// <summary>
///
/// </summary>
public EIIByte()
{
m_nSize = 0;
} /// <summary>
/// 重新设置
/// </summary>
/// <param name="nNewSize"></param>
public void SetSize(int nNewSize)
{
m_byte = new byte[nNewSize];
m_nSize= nNewSize;
}
/// <summary>
/// 初始化为0
/// </summary>
public void Reset()
{
m_byte.Initialize();
} /// <summary>
/// 返回缓存区
/// </summary>
/// <returns></returns>
public byte[] GetBuffer()
{
return m_byte;
} /// <summary>
/// 用新的缓存区替换
/// </summary>
/// <param name="bNew"></param>
public void SetBuffer( byte [] bNew)
{
m_byte = bNew;
m_nSize= bNew.Length;
} /// <summary>
/// 赋2bytes值
/// </summary>
/// <param name="n"></param>
/// <param name="?"></param>
public void SetWord(short n,ref int pos)
{
n = IPAddress.HostToNetworkOrder(n);
m_byte[pos] = Convert.ToByte((n>>8)%256);
m_byte[pos+1] = Convert.ToByte(n%256);
pos += 2;
} /// <summary>
/// 赋4bytes值
/// </summary>
/// <param name="n"></param>
/// <param name="?"></param>
public void SetDword(int n,ref int pos)
{
n = IPAddress.HostToNetworkOrder(n);
m_byte[pos] = Convert.ToByte((n>>24)%256);
m_byte[pos+1] = Convert.ToByte((n>>16)%256);
m_byte[pos+2] = Convert.ToByte((n>>8)%256);
m_byte[pos+3] = Convert.ToByte(n%256);
pos += 4;
} /// <summary>
/// 插入一段流
/// </summary>
/// <param name="nInsert"></param>
/// <param name="pos"></param>
public void SetByte(byte[] nInsert,ref int pos)
{
int n = nInsert.Length; for(int i=0 ; i<n; i++)
m_byte[pos+i] = nInsert[i]; pos += n;
} /// <summary>
/// 取出4bytes数据
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public int GetDword(ref int pos)
{
//组合
int n = m_byte[pos]<<24 + m_byte[pos+1]<<16 + m_byte[pos+2]<<8 + m_byte[pos+3];
//转化
n = IPAddress.NetworkToHostOrder(n); pos += 4; return n;
} /// <summary>
/// 取出2bytes数据
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public short GetWord(ref int pos)
{
//组合
short n = Convert.ToInt16(Convert.ToUInt16(m_byte[pos]<<8) + m_byte[pos+1]);
//转化
n = IPAddress.NetworkToHostOrder(n); pos += 2; return n;
} /// <summary>
/// 取出一段流
/// </summary>
/// <param name="nInsert"></param>
/// <param name="pos"></param>
public byte[] GetByte( int nLen,ref int pos)
{
byte[] bGet = new byte[nLen]; for(int i=0 ; i<nLen; i++)
bGet[i] = m_byte[pos+i] ; pos += nLen; return bGet;
}
/// <summary>
/// 赋2bytes值
/// </summary>
/// <param name="n"></param>
/// <param name="?"></param>
public void SetWord(byte[] buffer,short n,ref int pos)
{
n = IPAddress.HostToNetworkOrder(n);
buffer[pos] = Convert.ToByte((n>>8)%256);
buffer[pos+1] = Convert.ToByte(n%256);
pos += 2;
} /// <summary>
/// 赋4bytes值
/// </summary>
/// <param name="n"></param>
/// <param name="?"></param>
public void SetDword(byte[] buffer,int n,ref int pos)
{
n = IPAddress.HostToNetworkOrder(n);
buffer[pos] = Convert.ToByte((n>>24)%256);
buffer[pos+1] = Convert.ToByte((n>>16)%256);
buffer[pos+2] = Convert.ToByte((n>>8)%256);
buffer[pos+3] = Convert.ToByte(n%256);
pos += 4;
} /// <summary>
/// 插入一段流
/// </summary>
/// <param name="nInsert"></param>
/// <param name="pos"></param>
public void SetByte(byte[] buffer,byte[] nInsert,ref int pos)
{
int n = nInsert.Length; for(int i=0 ; i<n; i++)
buffer[pos+i] = nInsert[i]; pos += n;
} /// <summary>
/// 取出4bytes数据
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public int GetDword(byte[] buffer,ref int pos)
{
//组合
int n = buffer[pos]<<24 + buffer[pos+1]<<16 + buffer[pos+2]<<8 + buffer[pos+3];
//转化
n = IPAddress.NetworkToHostOrder(n); pos += 4; return n;
} /// <summary>
/// 取出2bytes数据
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public short GetWord(byte[] buffer,ref int pos)
{
//组合
short n = Convert.ToInt16(Convert.ToUInt16(buffer[pos]<<8) + buffer[pos+1]);
//转化
n = IPAddress.NetworkToHostOrder(n); pos += 2; return n;
} /// <summary>
/// 取出一段流
/// </summary>
/// <param name="nInsert"></param>
/// <param name="pos"></param>
public byte[] GetByte( byte[] buffer,int nLen,ref int pos)
{
byte[] bGet = new byte[nLen]; for(int i=0 ; i<nLen; i++)
bGet[i] = buffer[pos+i] ; pos += nLen; return bGet;
}
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;using EII.Base;namespace EII.Upload
{ /// <summary>
/// TUploadServer 的摘要说明。
/// </summary>
class TUploadServer
{
private Socket sWait = null; //wait Socket
private EIIByte m_byte = null;
private ASCIIEncoding m_ascn ;
/// <summary>
/// Const define
/// </summary>
private const int PORT = 5656; private const int MAX_CONNECT = 50;
#if LAN
private const int ONCE_COUNT = 1024 * 1024; //once count byte
#else
private const int ONCE_COUNT = 1024;
#endif const int OPEN_FILE_FAILED = 2,
FILE_ALWAYS_OPENED = 3,
ALL_RIGHT = 1;
const short CMD_C_REQUERY = 0x0301, //客户端发送要求上传命令
CMD_S_REQUERY = 0x0302, //服务器响应
CMD_C_DETAIL = 0x0303, //客户端发送上传文件内容
CMD_S_DETAIL = 0x0304, //响应
CMD_S_CHECK = 0x0306; //服务器心跳检测 private int nSocketNum =0;
private TSocketPacket[] aSock; private byte[] bSend;
private byte[] bCheck; protected AsyncCallback pfnWorkerCallBack ;
protected AsyncCallback proOnAccept ; /// <summary>
/// 上传文件包
/// </summary>
public class TSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[ONCE_COUNT]; public FileStream m_file ;
public int nTimes ;
public int nCurTime ;
public TSocketPacket()
{
Reset();
} /// <summary>
/// 清空
/// </summary>
public void Reset()
{ nTimes = 0;
nCurTime = 0;
if(m_file != null)
{
try
{
m_file.Flush();
m_file.Close();
}
catch
{
} finally
{
m_file = null;
}
} if( thisSocket != null)
{
try
{
thisSocket.Close();
}
catch
{
}
finally
{
thisSocket = null;
}
}
} // public bool bCmd = true;
}
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
// TcpListener myList=new TcpListener(ipAd,PORT);
//
// myList.Start(); TUploadServer app = new TUploadServer();
if(args.Length != 0)
app.CreateWait(Convert.ToInt16(args[0]));
else
app.CreateWait(); //
// TODO: 在此处添加代码以启动应用程序
//
}
/// <summary>
/// 构造
/// </summary>
public TUploadServer()
{
//Socket Packet Array
aSock = new TSocketPacket[MAX_CONNECT];
for(int i = 0; i< MAX_CONNECT; i++)
aSock[i] = new TSocketPacket(); // byte process
m_byte = new EIIByte(); nSocketNum = 0; bSend = new byte[ONCE_COUNT]; m_ascn = new ASCIIEncoding(); pfnWorkerCallBack = new AsyncCallback(OnDataReceived); proOnAccept = new AsyncCallback(OnAccept); bCheck = new Byte[2];
int pos = 0; m_byte.SetWord(bCheck,CMD_S_CHECK,ref pos);
}
/// <summary>
/// 创建等待连接
/// </summary>
public void CreateWait(int port)
{
int nCount = 0;
IPAddress ip = Dns.GetHostByName(Dns.GetHostName()).AddressList[0]; // IPAddress ipAddress = IPAddress.Parse(IP);
IPEndPoint ipe = new IPEndPoint(ip,port); sWait = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sWait.Bind(ipe);
sWait.Listen(MAX_CONNECT);
sWait.BeginAccept(proOnAccept,sWait); Console.WriteLine("The server is running at port {0}...",port);
Console.WriteLine("The local End point is :" + ip.ToString() );
Console.WriteLine("Waiting for a connection.....");
while(true)
{
System.Threading.Thread.Sleep(50);
nCount ++;
//每60秒检查一次
if(nCount >= 1200)
{
ActiveCheck();
nCount = 0;
}
}
} /// <summary>
/// 创建等待连接
/// </summary>
public void CreateWait()
{
CreateWait(PORT);
}
/// <summary>
/// 等待接收数据
/// </summary>
/// <param name="nIndex"></param>
private void WaitForData(int nIndex)
{
// Console.WriteLine("WaitForData {0}",soc.RemoteEndPoint.ToString());
try
{
TSocketPacket theSocPkt = aSock[nIndex]; if( theSocPkt == null)
return ;
// now start to listen for any data...
theSocPkt.thisSocket .BeginReceive (theSocPkt.dataBuffer ,0,theSocPkt.dataBuffer.Length ,SocketFlags.None,pfnWorkerCallBack,nIndex);
} catch(SocketException se)
{
ProcessSocketException(se,nIndex);
} }
/// 接收数据,并处理
/// </summary>
/// <param name="asyn"></param>
public void OnDataReceived(IAsyncResult asyn)
{
//send : CMD(WORD = 0x0301)+filename's length(WORD)+filename(target)+size(DWORD)+times(WORD),
//Receive: CMD(WORD = 0x0302)+reday status(BYTE 1= OK,2 = FAIL) //check
if( !((asyn.AsyncState) is int))
return; string sFileName = null;
short nNameLength = 0;
int nSize = 0;
byte byOper = ALL_RIGHT; //打开文件操作结果代码 int nIndex = (int)asyn.AsyncState; if(nIndex >= MAX_CONNECT || nIndex <0 )
return ;
TSocketPacket theSockId = aSock[nIndex] ; if(theSockId == null)
return ; try
{
//end receive...
int iRx = theSockId.thisSocket.EndReceive (asyn);
// Console.WriteLine("Received Data From {0},length = {1}",theSockId.thisSocket.RemoteEndPoint.ToString(),iRx);
int pos = 0; int nCmd = m_byte.GetWord(theSockId.dataBuffer,ref pos); if(nCmd == CMD_C_REQUERY) //requery
{ nNameLength = m_byte.GetWord(theSockId.dataBuffer,ref pos);
sFileName = m_ascn.GetString(theSockId.dataBuffer,pos,nNameLength); pos += nNameLength; nSize = m_byte.GetDword(theSockId.dataBuffer,ref pos); theSockId.nTimes= m_byte.GetDword(theSockId.dataBuffer,ref pos); Console.WriteLine("Get Requery file = '{0}',size = {1} ,times= {2}",sFileName,nSize,theSockId.nTimes); // assert m_file not opened
if (theSockId.m_file != null)
//return ;
byOper = FILE_ALWAYS_OPENED; try //open the file
{ theSockId.m_file = File.Open(sFileName,FileMode.OpenOrCreate,FileAccess.Write,FileShare.None ); Console.WriteLine("Open or Create file '{0}'",sFileName); byOper = ALL_RIGHT; theSockId.nCurTime = 0; } catch(Exception e)
{
Console.WriteLine(e.Message+","+sFileName);
byOper = OPEN_FILE_FAILED;
} //组织回应命令
pos = 0; m_byte.SetWord(bSend,CMD_S_REQUERY,ref pos); m_byte.SetByte(bSend,new byte[]{byOper},ref pos);
theSockId.thisSocket.Send(bSend,0,pos,SocketFlags.None );
}
else if(nCmd == CMD_C_DETAIL) //detail
{
// Console.WriteLine("Recevied file detail info {0} times",nCurTime);
// assert m_file is opened
if(theSockId.m_file == null)
return ;
//close
theSockId.nCurTime = m_byte.GetDword(theSockId.dataBuffer,ref pos); theSockId.m_file.Write(theSockId.dataBuffer, pos,iRx - pos); //每十个包保存一次
if((theSockId.nCurTime /10 ) == 0)
//save
theSockId.m_file.Flush(); //组织回应命令
pos = 0; m_byte.SetWord(bSend,CMD_S_DETAIL,ref pos);
m_byte.SetDword(bSend,theSockId.nCurTime,ref pos);
theSockId.thisSocket.Send(bSend,0,pos,SocketFlags.None); if( theSockId.nCurTime == theSockId.nTimes )
{
//save
theSockId.m_file.Flush();
theSockId.m_file.Close();
theSockId.m_file = null;
theSockId.nTimes = 0;
// sFileName= null;
} }
WaitForData(nIndex ); }
catch(SocketException se)
{
ProcessSocketException(se,nIndex);
}
}
/// <summary>
/// 接受新连接,并保存到连接数组
/// </summary>
/// <param name="ar"></param>
private void OnAccept(IAsyncResult ar)
{
try
{
Socket sWait = (Socket)ar.AsyncState;
//new connect socket
Socket sNew = sWait.EndAccept(ar);
sWait.BeginAccept(proOnAccept,sWait);
Console.Write(sNew.RemoteEndPoint.ToString());
// 超过最大连接数
if(nSocketNum >= MAX_CONNECT)
{
sNew.Close();
return ;
}
for(int i =0; i< MAX_CONNECT ; i++)
{
if(aSock[i].thisSocket == null)
{
aSock[i].thisSocket = sNew; //insert
WaitForData(i);
nSocketNum ++;
Console.WriteLine(" insert a Socket ,position = {0},count = {1}",i,nSocketNum);
break;
} }
}
catch(ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0,"1","\n OnClientConnection: Socket has been closed\n");
}
catch(SocketException se)
{
Console.WriteLine ( se.Message );
} //
}
/// <summary>
/// 处理连接错误,断开连接,释放资源
/// </summary>
/// <param name="se"></param>
/// <param name="nIndex"></param>
private void ProcessSocketException(SocketException se,int nIndex)
{
if(se != null)
Console.WriteLine ("Error code = {0},message = '{1}'",se.ErrorCode,se.Message ); //断开连接
if(aSock[nIndex].thisSocket != null)
{
aSock[nIndex].Reset();
if( nSocketNum > 0)
nSocketNum --;
Console.WriteLine("remove a Client Socket ,position= {0},count = {1}",nIndex,nSocketNum);
}
}
/// <summary>
/// 活动检测
/// </summary>
private void ActiveCheck()
{
for(int i =0, j= 0; (i< MAX_CONNECT) &&( j < nSocketNum); i++)
{
if(aSock[i].thisSocket == null)
continue;
try
{
if(aSock[i].thisSocket.Connected )
aSock[i].thisSocket.Send(bCheck);
else
ProcessSocketException(null,i);
}
catch(Exception )
{
ProcessSocketException(null,i);
} j ++;
}
} }
}
//////////////
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Text;using EII.Base;
namespace Twindow
{
public enum UploadException
{
OPEN_FILE_FAILED = -9,
CONNECT_FAILED ,
OTHER ,
OK = 0
}
/// <summary>
/// UpLoad 的摘要说明。
/// </summary>
public class UpLoad
{
private const int PORT = 5656; //upload port
private const int ONCE_COUNT= 1024; //once count byte
private const string IP = "172.16.36.77"; private AsyncCallback proSend = null;
private IAsyncResult m_asynResult;
public AsyncCallback pfnCallBack ;
private Socket m_Socket;
private ASCIIEncoding m_asen; private EIIByte m_byte; private int m_nPut = 0;
/// <summary>
/// SocketPacket
/// </summary>
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
} /// <summary>
/// 构造
/// </summary>
public UpLoad()
{
proSend = new AsyncCallback(OnSend);
m_nPut = 0;
m_asen=new ASCIIEncoding(); m_byte = new EIIByte(ONCE_COUNT);
}
/// <summary>
/// 连接
/// </summary>
public bool Connect()
{
return Connect(IP);
} /// <summary>
/// 连接到指定的IP
/// </summary>
/// <param name="sIP"></param>
public bool Connect(string sIP)
{
try
{
//create the socket instance...
m_Socket = new Socket (AddressFamily.InterNetwork,SocketType.Stream ,ProtocolType.Tcp ); // get the remote IP address...
IPAddress ip = IPAddress.Parse (sIP);
//create the end point
IPEndPoint ipEnd = new IPEndPoint (ip.Address,PORT);
//connect to the remote host...
m_Socket.Connect ( ipEnd );
//watch for data ( asynchronously )...
WaitForData(); return true;
}
catch(SocketException se)
{
Console.WriteLine (se.Message );
return false;
}
} /// <summary>
/// 等待接受数据
/// </summary>
public void WaitForData()
{
try
{
if ( pfnCallBack == null )
{
pfnCallBack = new AsyncCallback (OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket ();
theSocPkt.thisSocket = m_Socket;
// now start to listen for any data...
m_asynResult = m_Socket.BeginReceive (theSocPkt.dataBuffer ,0,theSocPkt.dataBuffer.Length ,SocketFlags.None,pfnCallBack,theSocPkt);
}
catch(SocketException se)
{
Console.WriteLine (se.Message );
} }
/// <summary>
/// 接受数据
/// </summary>
/// <param name="asyn"></param>
public void OnDataReceived(IAsyncResult asyn)
{
m_nPut = 0;
//Receive: CMD(WORD = 0x0302)+reday status(BYTE 1= OK,2 = FAIL) try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ;
//end receive...
int iRx = theSockId.thisSocket.EndReceive (asyn); if (iRx != 3)
m_nPut = 2;
else
{
m_byte.SetBuffer(theSockId.dataBuffer);
int pos = 0;
if((0x0302 != m_byte.GetWord(ref pos ) || (1 != m_byte.GetByte(1,ref pos)[0])))
m_nPut = 2; else
m_nPut = 1; }
//BH txtDataRx.Text = txtDataRx.Text + szData;
WaitForData();
}
catch (ObjectDisposedException )
{
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
}
catch(SocketException se)
{
Console.WriteLine (se.Message );
}
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="filename">要上传的文件名</param>
public UploadException SendFile(string filename,string targetname)
{
//send : CMD(WORD = 0x0301)+filename's length(WORD)+filename(target)+size(DWORD)+times(WORD),
//Receive: CMD(WORD = 0x0302)+reday status(BYTE 1= OK,2 = FAIL)
if(!m_Socket.Connected )
return UploadException.CONNECT_FAILED; //return value
UploadException re = UploadException.OK;
//file
FileStream file = null;
//file size
int size ;
//Upload times
int times ; int nTimes = 0;
try // try to open the file
{
file = File.OpenRead(filename); size = (int)file.Length; times = size/(ONCE_COUNT -2); m_byte.Reset(); int nFileNameLength = m_asen.GetByteCount(targetname); int pos = 0; //put data position m_byte.SetWord(0x0302,ref pos);
m_byte.SetWord((short)nFileNameLength,ref pos);
m_byte.SetByte(m_asen.GetBytes(targetname),ref pos);
m_byte.SetDword(size,ref pos);
m_byte.SetWord((short)times,ref pos);
byte[] bSend = m_byte.GetBuffer(); // m_Socket.BeginSend(bSend,0,bSend.Length,SocketFlags.None,proSend,m_Socket);//Send(bSend);
//等待回应
while(m_nPut == 0 && nTimes < 100)
{
// if( 0 != m_Socket.Receive(bSend))
// m_nPut = 2;
System.Threading.Thread.Sleep(200) ;
nTimes ++; }
if(m_nPut == 2)
return UploadException.OTHER; //组织发送包
for(int i =0; i< times; i++)
{
pos = 0;
m_byte.SetWord(bSend,0x0303,ref pos); //cmd
int n = file.Read(bSend,i*(ONCE_COUNT -2 ) + 2,ONCE_COUNT -2 );
m_Socket.Send(bSend,n + 2, SocketFlags.None );
// m_Socket.BeginSend(bSend,0,n,SocketFlags.None,proSend,m_Socket);
}
}
catch(SocketException) // 访问 Socket 时发生操作系统错误。
{
re = UploadException.CONNECT_FAILED;
}
catch(ObjectDisposedException) // Socket 已关闭。
{
re = UploadException.CONNECT_FAILED;
}
catch(ArgumentException ) //path 是一个零长度字符串、仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。
{
re = UploadException.OPEN_FILE_FAILED;
}
catch(PathTooLongException ) //path 的长度或 path 的绝对路径信息超过了系统定义的最大长度。
{
re = UploadException.OPEN_FILE_FAILED;
}
catch(DirectoryNotFoundException ) //未找到 path 中指定的目录。
{
re = UploadException.OPEN_FILE_FAILED;
}
catch(UnauthorizedAccessException ) //path 指定了一个只读文件。path 指定了一个目录。
{
re = UploadException.OPEN_FILE_FAILED;
}
catch(FileNotFoundException ) //未找到 path 中指定的文件。
{
re = UploadException.OPEN_FILE_FAILED; }
catch
{
re = UploadException.OPEN_FILE_FAILED;
} finally //close the file
{
if(file != null)
file.Close();
} return re; // file.Read(bSend,i*ONCE_COUNT,ONCE_COUNT);
// m_Socket.Send(newbyte); } /// <summary>
/// 接受连接
/// </summary>
/// <param name="ar"></param>
private void OnConnect(IAsyncResult ar)
{
m_Socket.EndConnect(null);
} /// <summary>
/// 结束传送
/// </summary>
/// <param name="ar"></param>
private void OnSend(IAsyncResult ar)
{
m_Socket.EndSend(ar);
} public static int Main(string[] args)
{
UpLoad app = new UpLoad();
//等待反应
Console.Read();
//连接
if(!app.Connect())
return -1; //上传
if(args.Length > 1)
app.SendFile(args[0],args[1]);
else
app.SendFile("C:\test.dat","d:\test.dat"); return 0;
} }
}
谢谢!