码迷,mamicode.com
首页 > 其他好文 > 详细

Socket大文件上传

时间:2014-07-17 22:09:52      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   文件   

bubuko.com,布布扣
 1     public sealed class SocketData
 2     {
 3         private SocketData()
 4         {
 5         }
 6 
 7         public static SendFileMode SendFile(Socket socket, string fileName, int maxBufferLength)
 8         {
 9             SendFileMode flag = SendFileMode.Success;
10             try
11             {
12                 using (Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
13                 {
14                     long fileLength = fs.Length;
15                     long leftLength = fileLength;
16                     int readLength = 0;
17                     byte[] buffer = null;
18                     var file_name = System.IO.Path.GetFileName(fileName);
19                     var bytefileName = System.Text.Encoding.UTF8.GetBytes(file_name + "|" + fs.Length);
20                     socket.Send(bytefileName);
21                     if (fileLength <= maxBufferLength)
22                     {            /* 文件可以一次读取*/
23                         buffer = new byte[fileLength];
24                         readLength = fs.Read(buffer, 0, (int)fileLength);
25                         //开始发送
26                         socket.Send(buffer, SocketFlags.None);
27                     }
28                     else
29                     {
30                         while (leftLength != 0)
31                         {
32                             if (leftLength < maxBufferLength)
33                             {
34                                 buffer = new byte[leftLength];
35                                 readLength = fs.Read(buffer, 0, Convert.ToInt32(leftLength));
36                             }
37                             else
38                             {
39                                 buffer = new byte[maxBufferLength];
40                                 readLength = fs.Read(buffer, 0, maxBufferLength);
41                             }
42                             //开始发送
43                             socket.Send(buffer, SocketFlags.None);
44                             leftLength -= readLength;
45                         }
46                     }
47                 }
48             }
49             catch (IOException)
50             {
51 
52                 flag = SendFileMode.IOException;
53             }
54             return flag;
55         }
56     }
SocketData

 

bubuko.com,布布扣
1     public enum SendFileMode
2     {
3         IOException = -4,
4         TimeOut = -1,
5         Success = 0,
6         SendFileError = -2,
7         SocketException=-3
8     }
SendFileMode

Socket大文件上传,布布扣,bubuko.com

Socket大文件上传

标签:style   blog   http   color   os   文件   

原文地址:http://www.cnblogs.com/gaobing/p/3851740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!