打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C# Socket传输大文件
userphoto

2017.03.12

关注

1.基础类TransferFiles,client和server都需要

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4.   
  5. using System.Net;  
  6. using System.Net.Sockets;  
  7. using System.Windows.Forms;  
  8.   
  9.   
  10. namespace Server  
  11. {  
  12.     public class TransferFiles  
  13.     {  
  14.         public static int SendData(Socket s, byte[] data)  
  15.         {  
  16.             int total = 0;  
  17.             int size = data.Length;  
  18.             int dataleft = size;  
  19.             int sent;  
  20.   
  21.             while (total < size)  
  22.             {  
  23.                 sent = s.Send(data, total, dataleft, SocketFlags.None);  
  24.                 total += sent;  
  25.                 dataleft -= sent;  
  26.             }  
  27.   
  28.             return total;  
  29.         }  
  30.   
  31.   
  32.         public static byte[] ReceiveData(Socket s, int size)  
  33.         {  
  34.             int total = 0;  
  35.             int dataleft = size;  
  36.             byte[] data = new byte[size];  
  37.             int recv;  
  38.             while (total < size)  
  39.             {  
  40.                 recv = s.Receive(data, total, dataleft, SocketFlags.None);  
  41.                 if (recv == 0)  
  42.                 {  
  43.                     data = null;  
  44.                     break;  
  45.                 }  
  46.   
  47.                 total += recv;  
  48.                 dataleft -= recv;  
  49.             }  
  50.             return data;  
  51.         }  
  52.   
  53.         public static int SendVarData(Socket s, byte[] data)  
  54.         {  
  55.             int total = 0;  
  56.             int size = data.Length;  
  57.             int dataleft = size;  
  58.             int sent;  
  59.             byte[] datasize = new byte[4];  
  60.   
  61.             try  
  62.             {  
  63.                 datasize = BitConverter.GetBytes(size);  
  64.                 sent = s.Send(datasize);  
  65.   
  66.                 while (total < size)  
  67.                 {  
  68.                     sent = s.Send(data, total, dataleft, SocketFlags.None);  
  69.                     total += sent;  
  70.                     dataleft -= sent;  
  71.                 }  
  72.   
  73.                 return total;  
  74.             }  
  75.             catch  
  76.             {  
  77.                 return 3;  
  78.   
  79.             }  
  80.         }  
  81.   
  82.         public static byte[] ReceiveVarData(Socket s)  
  83.         {  
  84.             int total = 0;  
  85.             int recv;  
  86.             byte[] datasize = new byte[4];  
  87.             recv = s.Receive(datasize, 0, 4, SocketFlags.None);  
  88.             int size = BitConverter.ToInt32(datasize, 0);  
  89.             int dataleft = size;  
  90.             byte[] data = new byte[size];  
  91.             while (total < size)  
  92.             {  
  93.                 recv = s.Receive(data, total, dataleft, SocketFlags.None);  
  94.                 if (recv == 0)  
  95.                 {  
  96.                     data = null;  
  97.                     break;  
  98.                 }  
  99.                 total += recv;  
  100.                 dataleft -= recv;  
  101.             }  
  102.             return data;  
  103.         }  
  104.     }  
  105. }  


2.Server端

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Net;  
  5. using System.Net.Sockets;  
  6. using System.Threading;  
  7. using System.IO;  
  8. using System.Configuration;  
  9.   
  10. namespace Server  
  11. {  
  12.     public static class FileServer  
  13.     {  
  14.         private static Socket serverSocket;  
  15.         public static void Init()  
  16.         {  
  17.             //服务器IP地址  
  18.             IPAddress ip = IPAddress.Parse(ConfigurationManager.AppSettings["ListenIP"]);  
  19.             int myProt = Convert.ToInt32(ConfigurationManager.AppSettings["ListenFilePort"]);  
  20.             serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  21.             serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址:端口  
  22.             serverSocket.Listen(10);    //设定最多10个排队连接请求  
  23.             Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());  
  24.             //通过Clientsoket发送数据  
  25.             Thread myThread = new Thread(ListenClientConnect);  
  26.             myThread.Start();  
  27.         }  
  28.         public static void Exit()  
  29.         {  
  30.             serverSocket.Close();  
  31.             serverSocket = null;  
  32.         }  
  33.         private static void ListenClientConnect()  
  34.         {  
  35.             while (true)  
  36.             {  
  37.                 if (serverSocket != null)  
  38.                 {  
  39.                     try  
  40.                     {  
  41.                         Socket clientSocket = serverSocket.Accept();  
  42.                         Thread receiveThread = new Thread(Create);  
  43.                         receiveThread.Start(clientSocket);  
  44.                     }  
  45.                     catch  
  46.                     {  
  47.                         break;  
  48.                     }  
  49.                 }  
  50.             }  
  51.         }  
  52.         public static void Create(object clientSocket)  
  53.         {  
  54.             Socket client = clientSocket as Socket;  
  55.             //获得客户端节点对象  
  56.             IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;              
  57.   
  58.             //获得[文件名]     
  59.             string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));  
  60.   
  61.             //检查是否使用本地媒体库  
  62.             if (SocketServer.useLocal)  
  63.             {  
  64.                 //关闭套接字     
  65.                 client.Close();  
  66.                 return;  
  67.             }  
  68.   
  69.             //获得[包的大小]     
  70.             string bagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));  
  71.   
  72.             //获得[包的总数量]     
  73.             int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));  
  74.   
  75.             //获得[最后一个包的大小]     
  76.             string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));  
  77.   
  78.   
  79.             string fullPath = Path.Combine(Environment.CurrentDirectory,SendFileName);  
  80.             //创建一个新文件     
  81.             FileStream MyFileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write);  
  82.   
  83.             //已发送包的个数     
  84.             int SendedCount = 0;  
  85.             while (true)  
  86.             {  
  87.   
  88.                 byte[] data = TransferFiles.ReceiveVarData(client);  
  89.                 if (data.Length == 0)  
  90.                 {  
  91.                     break;  
  92.                 }  
  93.                 else  
  94.                 {                      
  95.                     SendedCount++;  
  96.                     //将接收到的数据包写入到文件流对象     
  97.                     MyFileStream.Write(data, 0, data.Length);  
  98.                     //显示已发送包的个数       
  99.   
  100.                 }  
  101.             }  
  102.             //关闭文件流     
  103.             MyFileStream.Close();  
  104.             //关闭套接字     
  105.             client.Close();  
  106.             SocketServer.pForm.ShowMessageBox(SendFileName + "接收完毕!");  
  107.         }  
  108.     }  
  109. }  

3.Client端

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.IO;  
  5. using System.Net;  
  6. using System.Net.Sockets;  
  7. using System.Diagnostics;  
  8.   
  9. namespace Client  
  10. {  
  11.     public static class FileClient  
  12.     {  
  13.         public static bool SendFile(string IP,int Port,string fullPath)  
  14.         {  
  15.             //创建一个文件对象  
  16.             FileInfo EzoneFile = new FileInfo(fullPath);  
  17.             //打开文件流  
  18.             FileStream EzoneStream = EzoneFile.OpenRead();  
  19.   
  20.             //包的大小  
  21.             int PacketSize = 10000;  
  22.   
  23.             //包的数量  
  24.             int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));  
  25.   
  26.             //最后一个包的大小  
  27.             int LastDataPacket = (int)(EzoneStream.Length - ((long)(PacketSize * PacketCount)));  
  28.   
  29.             //指向远程服务端节点  
  30.             IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(IP), Port);  
  31.   
  32.             //创建套接字  
  33.             Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  34.   
  35.             //连接到发送端  
  36.             try  
  37.             {  
  38.                 client.Connect(ipep);  
  39.             }  
  40.             catch  
  41.             {  
  42.                 Debug.WriteLine("连接服务器失败!");  
  43.                 return false;  
  44.             }  
  45.             //获得客户端节点对象  
  46.             IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;  
  47.   
  48.   
  49.             //发送[文件名]到客户端  
  50.             TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(EzoneFile.Name));  
  51.   
  52.             //发送[包的大小]到客户端  
  53.             TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketSize.ToString()));  
  54.   
  55.             //发送[包的总数量]到客户端  
  56.             TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketCount.ToString()));  
  57.   
  58.             //发送[最后一个包的大小]到客户端  
  59.             TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastDataPacket.ToString()));  
  60.   
  61.             bool isCut = false;  
  62.             //数据包  
  63.             byte[] data = new byte[PacketSize];  
  64.             //开始循环发送数据包  
  65.             for (int i = 0; i < PacketCount; i++)  
  66.             {  
  67.                 //从文件流读取数据并填充数据包  
  68.                 EzoneStream.Read(data, 0, data.Length);  
  69.                 //发送数据包  
  70.                 if (TransferFiles.SendVarData(client, data) == 3)  
  71.                 {                      
  72.                     isCut = true;  
  73.                     return false;  
  74.                     break;  
  75.                 }  
  76.   
  77.             }  
  78.   
  79.             //如果还有多余的数据包,则应该发送完毕!  
  80.             if (LastDataPacket != 0)  
  81.             {  
  82.                 data = new byte[LastDataPacket];  
  83.                 EzoneStream.Read(data, 0, data.Length);  
  84.                 TransferFiles.SendVarData(client, data);  
  85.             }  
  86.   
  87.             //关闭套接字  
  88.             client.Close();  
  89.             //关闭文件流  
  90.             EzoneStream.Close();  
  91.             if (!isCut)  
  92.             {  
  93.                 return true;  
  94.             }  
  95.             return false;  
  96.         }  
  97.     }  
  98. }  




本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Unity中的多屏以及最大化最小化
用TCP/IP实现自己简单的应用程序协议:成帧器部分
TCP本地通信 简单程序实现 (一)
C# TCP Socket通信服务端
Python基于TCP与UDP协议实现Socket通信
3个学习Socket编程的简单例子:TCP Server/Client, Select
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服