/// <summary> /// 循环监听 /// </summary> void listen() { Socket sockets; byte[] data; try { sockets = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sockets.Bind(localIpe); } catch { return; } while (true) { try { sockets.Listen(200); Socket newSocket = sockets.Accept(); using (MemoryStream ms = new MemoryStream()) { byte[] btMsg = new byte[10240]; int t = 1; while (t > 0) { t = newSocket.Receive(btMsg); ms.Write(btMsg, 0, t); } data = ms.ToArray(); } newSocket.Close(); NetOrder no = new NetOrder(data); no.Root = Root; no.LocalIPE = localIpe; new NetOrderDealer(no).Run(); if (RecievedOrder != null) { RecievedOrder(this, no); } Thread.Sleep(1); } catch (SocketException ex) { Console.WriteLine(ex.Message); } } }
void download() { Socket sockets = null; //用于传输的Socket类。 byte[] fileData = null; //文件数据。 byte[] tempBytes = null; //临时缓冲数据。 DataDownloadEvenetArgs e = new DataDownloadEvenetArgs(); e.RecieverIp = localIpe; e.SenderIp = remoteIpe; try { sockets = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sockets.Bind(localIpe); sockets.Listen(5); //发送连接请求, 某路径没数据,那么变为等待状态。 if (filePath != null && filePath.Length > 0) { DataSender ds = new DataSender(localIpe, remoteIpe); if (filePath.ToLower() == "xml") { ds.SendOrder("XML"); } else { ds.SendOrder("GetFile", filePath); } } //等待接收数据。 Socket newSocket = sockets.Accept(); //先读取头文件。 tempBytes = new byte[1024]; newSocket.Receive(tempBytes); NetOrder no = new NetOrder(tempBytes); e.StartTime = DateTime.Now; if (no.OrderName == "FileData") { //开始接收数据。 downloading = true; filePath = no.Parameter[0]; fileSize = int.Parse(no.Parameter[1]); //再读取后面的数据。t用于表示每次读取到的数据长度。 MemoryStream ms = new MemoryStream(); tempBytes = new byte[blockSize]; int t = 1; while (t > 0) { t = newSocket.Receive(tempBytes); downloadedSize += t; ms.Write(tempBytes, 0, t); } //接收数据到fileData fileData = ms.ToArray(); e.EndTime = DateTime.Now; //关闭所有相关资源。 newSocket.Close(); sockets.Close(); ms.Close(); downloading = false; //保存文件。 SaveFile(fileData); completeDownload = true; e.Data = fileData; e.Message = "文件接收成功。"; } else if (no.OrderName == "Error") { e.Message = no.Parameter[0]; e.Data = null; } } catch (Exception e1) { e.Data = null; e.Message = e1.Message; e.EndTime = DateTime.Now; } if (DownloadComplete != null) { DownloadComplete(this, e); } }
/// <summary> /// NetOrder处理类,专门用于命令类的处理。 /// </summary> /// <param name="no"></param> public NetOrderDealer(NetOrder no) { order = no; }