C# Socket实现断点上传文件

  1  public partial class VAV_File_Client
2 {
3 private string path = "";
4 private string strBaseDir = "";
5 private string host = "";
6 private int port1 = 0;
7 private int port2 = 0;
8 private int port3 = 0;
9 private bool IsXuChuan = false;
10 private bool IsFuGai = false;
11 private int BackDay = 0;
12 private int SIZEBUFFER = 0;
13
14 public VAV_File_Client()
15 {
16 path = System.Configuration.ConfigurationManager.AppSettings["APPEmailXML"].ToString();
17 strBaseDir = System.Configuration.ConfigurationManager.AppSettings["strBaseDir"].ToString();
18 host = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
19 port1 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port1"].ToString());
20 port2 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port2"].ToString());
21 port3 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port3"].ToString());
22 IsXuChuan = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsXuChuan"].ToString());
23 IsFuGai = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsFuGai"].ToString());
24 BackDay = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["BackDay"].ToString());
25 SIZEBUFFER = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SIZEBUFFER"].ToString());
26 }
27 /// <summary>
28 /// 启动
29 /// </summary>
30 public void start()
31 {
32 try
33 {
34 GetAllDirList(strBaseDir, BackDay);
35 foreach (string pathDir in al)
36 {
37 if (pathDir.Contains("\t<目录>"))
38 {
39 string ddddS = pathDir.Substring(pathDir.IndexOf(strBaseDir) + strBaseDir.Length);
40 scoketSend(host, port2, Encoding.UTF8.GetBytes(ddddS)); //传输文件名称
41 sendFlie(host, port1, pathDir, IsXuChuan, IsFuGai);//传输文件
42 continue;
43 }
44 //string fileName = pathDir.Substring(pathDir.LastIndexOf("\\") + 1);
45 string fileName = pathDir.Substring(pathDir.IndexOf(strBaseDir) + strBaseDir.Length);
46
47 byte[] bs = Encoding.UTF8.GetBytes(fileName);
48
49 scoketSend(host, port2, bs); //传输文件名称
50
51 sendFlie(host, port1, pathDir, IsXuChuan, IsFuGai);//传输文件
52
53 DelFile(pathDir);
54 }
55 }
56 catch (ArgumentNullException e)
57 {
58 Console.WriteLine("ArgumentNullException: {0}", e);
59 }
60 catch (SocketException e)
61 {
62 Console.WriteLine("SocketException: {0}", e);
63 }
64 Console.WriteLine("end");
65 }
66
67
68 //连接服务器发送数据
69 /// <summary>
70 ///
71 /// </summary>
72 /// <param name="host"></param>
73 /// <param name="port">2006</param>
74 /// <param name="bs"></param>
75 private void scoketSend(string host, int port, byte[] bs)
76 {
77
78 IPAddress ip = IPAddress.Parse(host);
79 // int port = 2006;
80 IPEndPoint ipe = new IPEndPoint(ip, port);
81 Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
82 c.Connect(ipe);
83 c.Send(bs, bs.Length, 0);
84 c.Close();
85 }
86 //连接服务器接收数据
87 /// <summary>
88 ///
89 /// </summary>
90 /// <param name="host"></param>
91 /// <param name="port">2006</param>
92 /// <returns></returns>
93 private string scoketReceive(string host, int port)
94 {
95 IPAddress ip = IPAddress.Parse(host);
96 // int port = 2006;
97 IPEndPoint ipe = new IPEndPoint(ip, port);
98 Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
99 c.Connect(ipe);
100 string startStr = "";
101 byte[] startBytes = new byte[SIZEBUFFER];
102 int bytess;
103 bytess = c.Receive(startBytes, startBytes.Length, 0);
104 startStr += Encoding.ASCII.GetString(startBytes, 0, bytess);
105 c.Close();
106 return startStr;
107 }
108 //传输文件名称
109 /// <summary>
110 ///
111 /// </summary>
112 /// <param name="path">127.0.0.1</param>
113 /// <param name="port">2006</param>
114 private void sendName(string host, int port, string path)
115 {
116 //string host = "127.0.0.1";
117 IPAddress ip = IPAddress.Parse(host);
118 //int port = 2006;
119 IPEndPoint ipe = new IPEndPoint(ip, port);
120 Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
121 c.Connect(ipe);
122
123 string fileName = path.Substring(path.LastIndexOf("\\") + 1);
124 //UTF8处理中文
125 byte[] bs = Encoding.UTF8.GetBytes(fileName);
126 c.Send(bs, bs.Length, 0);
127 c.Close();
128 }
129 //所传输的文件是否续传
130 /// <summary>
131 /// 所传输的文件是否续传
132 /// </summary>
133 /// <param name="str"></param>
134 /// <param name="host">127.0.0.1</param>
135 /// <param name="port">port = 2007</param>
136 /// <param name="xuchuan">是否续传</param>
137 public void setxc(string str, string host, int port, bool xuchuan)
138 {
139 IPAddress ip = IPAddress.Parse(host);
140
141 port = 2007;
142 IPEndPoint ipe = new IPEndPoint(ip, port);
143 Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
144 c.Connect(ipe);
145 string Str = str;
146 byte[] bxc = Encoding.ASCII.GetBytes(Str);
147 c.Send(bxc, bxc.Length, 0);
148 c.Close();
149 }
150
151 //传输文件/// <summary>
152 /// <summary>
153 ///
154 /// </summary>
155 /// <param name="host">"127.0.0.1"</param>
156 /// <param name="port">port = 2005;</param>
157 /// <param name="fileName">带路径的文件名</param>
158 /// <param name="xuchuan">是否需要续传</param>
159 /// <param name="cover">是否覆盖</param>
160 private void sendFlie(string host, int port, string fileName, bool xuchuan, bool IsFuGai)
161 {
162 try
163 {
164 IPAddress ip = IPAddress.Parse(host);
165 IPEndPoint ipe = new IPEndPoint(ip, port);
166 Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
167 c.Connect(ipe);//建立于远程主机的链接
168 //接收服务器返回存在的文件大小
169 byte[] startBytes = new byte[SIZEBUFFER];
170 string startStr = Encoding.ASCII.GetString(startBytes, 0, c.Receive(startBytes, startBytes.Length, 0));
171 //已接受文件长度
172 int startSet = int.Parse(startStr);
173 byte[] b = new byte[SIZEBUFFER]; //创建文件缓冲区,这里可以认为文件的最大值
174 if (fileName.Contains("\t<目录>"))
175 {
176 c.Close(); //关闭Socket
177 return;
178 }
179 FileStream file = File.Open(fileName, FileMode.Open, FileAccess.Read); //创建文件流
180 //文件字节总长度
181 int fileAllLength = (int)file.Length;
182 //文件剩余字节长度
183 int fileLast = startSet < fileAllLength ? fileAllLength - startSet : 0;
184
185 int intLength = 0;
186 #region 续传
187 if (startSet > 0 && startSet < fileAllLength && xuchuan == true)
188 {
189 //传输文件是否续传
190 setxc("xc", host, port3, xuchuan);
191 file.Seek(long.Parse(startStr), SeekOrigin.Begin); //移动文件流中的当前指针
192 intLength = int.Parse(startStr);
193 while (fileLast > 0)
194 {
195 int count = file.Read(b, 0, b.Length);
196 int readbytes = count >= b.Length ? b.Length : count;
197 readbytes = c.Send(b, 0, readbytes, SocketFlags.None);
198 Encoding.ASCII.GetString(startBytes, 0, c.Receive(startBytes, startBytes.Length, 0));
199 fileLast -= count;
200 intLength += count;
201 file.Seek(intLength, SeekOrigin.Begin);
202 if (fileLast == 0)
203 {
204 c.Send(Encoding.UTF8.GetBytes("end"), Encoding.UTF8.GetBytes("end").Length, 0);
205 }
206 }
207 }
208 #endregion
209 #region
210 else
211 {
212 if (fileLast == 0 && IsFuGai == false)
213 {
214 setxc("qx", host, port3, xuchuan);
215 }
216 else
217 {
218 //传输文件是否续传
219 setxc("bxc", host, port3, xuchuan);
220
221 while (fileLast > 0)
222 {
223 int count = file.Read(b, 0, b.Length);
224 int SdCount = fileLast < b.Length ? count : b.Length;
225 SdCount = c.Send(b, 0, SdCount, SocketFlags.None);
226 Encoding.ASCII.GetString(startBytes, 0, c.Receive(startBytes, startBytes.Length, 0));
227 fileLast -= count;//剩余的字节长度
228 intLength += count;//定位指针用
229 file.Seek(intLength, SeekOrigin.Begin);
230 if (fileLast == 0)
231 {
232 c.Send(Encoding.UTF8.GetBytes("end"), Encoding.UTF8.GetBytes("end").Length, 0);
233 }
234 Console.WriteLine("已传送字节: " + intLength);
235 }
236 }
237 }
238 #endregion
239 file.Close(); //关闭文件流
240 string recvStr = "";
241 byte[] recvBytes = new byte[SIZEBUFFER];
242 int bytes;
243 bytes = c.Receive(recvBytes, recvBytes.Length, 0);
244 recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
245 //MessageBox.Show(recvStr);
246 Console.WriteLine(recvStr);
247 c.Close(); //关闭Socket
248 }
249 catch (NullReferenceException e)
250 {
251 Console.WriteLine("{0}", e);
252 }
253 }
254
255 public ArrayList al = new ArrayList();//定义存储文件和文件夹名的数组
256 public int aaa = 0;//定义标志位参数,递归时判断该参数,若不为0则非第一次递归
257 /// <summary>
258 /// 获取指定某一天之前的文件,不包括当天
259 /// </summary>
260 /// <param name="strBaseDir">指定目录</param>
261 /// <param name="Day">指定天数</param>
262 public void GetAllDirList(string strBaseDir, int Day)
263 {
264 DirectoryInfo di = new DirectoryInfo(strBaseDir);
265 DirectoryInfo[] diA = di.GetDirectories();
266 if (aaa == 0)
267 {
268 FileInfo[] fis2 = di.GetFiles(); //有关目录下的文件
269 for (int i2 = 0; i2 < fis2.Length; i2++)
270 {
271
272 if (fis2[i2].CreationTime < DateTime.Now.AddDays(Day) && fis2[i2].FullName.Substring(fis2[i2].FullName.LastIndexOf("\\") + 1).StartsWith("DEL_") == false)//指定时间
273 {
274 al.Add(fis2[i2].FullName);
275 }
276 }
277 }
278 for (int i = 0; i < diA.Length; i++)
279 {
280 aaa++;
281 al.Add(diA[i].FullName + "\t<目录>");
282 //diA[i].FullName是某个子目录的绝对地址,把它记录在ArrayList中
283 DirectoryInfo di1 = new DirectoryInfo(diA[i].FullName);
284 DirectoryInfo[] diA1 = di1.GetDirectories();
285 FileInfo[] fis1 = di1.GetFiles(); //有关目录下的文件
286 for (int ii = 0; ii < fis1.Length; ii++)
287 {
288 if (fis1[ii].CreationTime < DateTime.Now.AddDays(Day) && fis1[ii].FullName.Substring(fis1[ii].FullName.LastIndexOf("\\") + 1).StartsWith("DEL_") == false)
289 {
290 al.Add(fis1[ii].FullName);
291 }
292 }
293 GetAllDirList(diA[i].FullName, Day);
294 }
295 }
296
297 /// <summary>
298 /// 删除文件
299 /// </summary>
300 /// <param name="FileName">文件名</param>
301 public void DelFile(string FileName)
302 {
303 FileInfo fInfo = new FileInfo(FileName);
304
305 fInfo.MoveTo(FileName.Replace(FileName.Substring(FileName.LastIndexOf("\\") + 1), "DEL_" + FileName.Substring(FileName.LastIndexOf("\\") + 1)));
306 }
307
308 private void DeleteInDir(string szDirPath)
309 {
310 if (szDirPath.Trim() == "" || !Directory.Exists(szDirPath))
311 return;
312 DirectoryInfo dirInfo = new DirectoryInfo(szDirPath);
313
314 FileInfo[] fileInfos = dirInfo.GetFiles();
315 if (fileInfos != null && fileInfos.Length > 0)
316 {
317 foreach (FileInfo fileInfo in fileInfos)
318 {
319
320 }
321 }
322
323 DirectoryInfo[] dirInfos = dirInfo.GetDirectories();
324 if (dirInfos != null && dirInfos.Length > 0)
325 {
326 foreach (DirectoryInfo childDirInfo in dirInfos)
327 {
328 DeleteInDir(childDirInfo.ToString()); //递归
329 }
330 }
331 }
332 }
  1  public partial class VAV_File_Server
2 {
3 private string PathFiles = "";
4 private string host = "";
5 private int port1 = 0;
6 private int port2 = 0;
7 private int port3 = 0;
8 private bool IsXuChuan = false;
9 private bool IsFuGai = false;
10 private int SIZEBUFFER = 0;
11
12 /// <summary>
13 /// 构造函数
14 /// </summary>
15 public VAV_File_Server()
16 {
17 //path = System.Configuration.ConfigurationManager.AppSettings["APPEmailXML"].ToString();
18 PathFiles = System.Configuration.ConfigurationManager.AppSettings["PathFiles"].ToString();
19 host = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
20 port1 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port1"].ToString());
21 port2 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port2"].ToString());
22 port3 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port3"].ToString());
23 IsXuChuan = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsXuChuan"].ToString());
24 IsFuGai = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsFuGai"].ToString());
25 SIZEBUFFER = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SIZEBUFFER"].ToString());
26 }
27 Socket s;
28 Socket s1;
29 Socket s2;
30 FileStream file;
31
32 public void start()
33 {
34
35 #region
36 try
37 {
38 IPAddress ip = IPAddress.Parse(host);
39 IPEndPoint ipe1 = new IPEndPoint(ip, port1);
40 IPEndPoint ipe2 = new IPEndPoint(ip, port2);
41 IPEndPoint ipe3 = new IPEndPoint(ip, port3);
42 //创建Socket 实例
43 s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
44 s1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
45 s2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
46 s1.Bind(ipe1);
47 s.Bind(ipe2);
48 s2.Bind(ipe3);
49 s.Listen(0);
50 s1.Listen(0);
51 s2.Listen(0);
52 while (true)
53 {
54 get();
55 }
56 s.Dispose();
57 s1.Dispose();
58 s2.Dispose();
59
60 }
61 catch (ArgumentNullException e)
62 {
63 Console.WriteLine("ArgumentNullException: {0}", e);
64
65 }
66 catch (SocketException e)
67 {
68 Console.WriteLine("SocketException: {0}", e);
69 }
70 // Console.ReadLine();
71 #endregion
72 }
73
74 private void get()
75 {
76 try
77 {
78 while (true)
79 {
80 //获取Socket连接
81 Console.WriteLine("等待接收2006发来的数据");
82 Socket ss = s.Accept();
83
84 Console.WriteLine("收到2006的数据");
85 Console.WriteLine("等待接收2005发来的数据");
86 Socket ss1 = s1.Accept();
87 Console.WriteLine("收到2005的数据");
88
89 //接收的文件名称
90 string recvStr = "";
91 if (ss.Connected) //确定连接
92 {
93 byte[] recvBytes = new byte[SIZEBUFFER];
94 int bytes;
95 bytes = ss.Receive(recvBytes, recvBytes.Length, 0);
96 //UTF8处理中文
97 recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
98 ss.Close();
99 }
100 string path = "";
101
102 path = @PathFiles.EndsWith("\\") ? PathFiles + Regex.Replace(recvStr, @"^\\", "") : PathFiles + "\\" + Regex.Replace(recvStr, @"^\\", ""); //存放接收的文件路径
103 if (path.Contains("\t<目录>"))//D:\\Down\\第一层\t<目录>
104 {
105 path = path.Replace("\t<目录>", "");
106 if (!Directory.Exists(path))
107 {
108 Directory.CreateDirectory(path);
109 }
110 ss1.Send(Encoding.ASCII.GetBytes("0"), Encoding.ASCII.GetBytes("0").Length, 0);
111 continue;
112 }
113 long lStartPos = 0;
114 if (File.Exists(path))
115 {
116 file = File.OpenWrite(path);
117 lStartPos = file.Length;
118 }
119 else
120 {
121 file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); //写入文件流
122 //file = new FileStream(path, FileMode.Create); //写入文件流
123 lStartPos = 0;
124 }
125
126 string startStr = lStartPos.ToString();
127 byte[] bstar = Encoding.ASCII.GetBytes(startStr);
128 ss1.Send(bstar, bstar.Length, 0);
129
130 if (ss1.Connected) //确定连接
131 {
132 Console.WriteLine("2005连接成功");
133 //接收文件是否续传
134 Console.WriteLine("2007接受文件是否续传");
135 Socket ss2 = s2.Accept();
136 string str = "";
137 if (ss2.Connected) //确定连接
138 {
139 byte[] xcBytes = new byte[SIZEBUFFER];
140 int bytes;
141 bytes = ss2.Receive(xcBytes, xcBytes.Length, 0);
142 str += Encoding.ASCII.GetString(xcBytes, 0, bytes);
143 ss2.Close();
144 }
145 if (str == "xc")
146 {
147 file.Seek(lStartPos, SeekOrigin.Current); //移动文件流中的当前指针
148 }
149 if (str == "bxc")
150 {
151 file.Close();
152 File.Delete(path);
153 file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); //写入文件流
154 }
155 if (str == "qx")
156 {
157 file.Close();
158 ss1.Shutdown(SocketShutdown.Both);
159 ss1.Close();
160
161 }
162 else
163 {
164
165 byte[] nbytes = new byte[SIZEBUFFER];
166 int nReadSize = 0;
167
168 nReadSize = ss1.Receive(nbytes, 0, nbytes.Length, SocketFlags.None);
169
170 ss1.Send(Encoding.ASCII.GetBytes(nReadSize.ToString()), Encoding.ASCII.GetBytes(nReadSize.ToString()).Length, 0); //返回接收到的数据
171 int TotleSize = nReadSize;
172
173 while (nReadSize > 0)
174 {
175 file.Write(nbytes, 0, nReadSize);
176
177 nReadSize = ss1.Receive(nbytes, 0, nbytes.Length, SocketFlags.None);
178
179 if (Encoding.UTF8.GetString(nbytes, 0, nReadSize) == "end")
180 {
181 break;
182 }
183 ss1.Send(Encoding.ASCII.GetBytes(nReadSize.ToString()), Encoding.ASCII.GetBytes(nReadSize.ToString()).Length, 0); //返回接收到的数据
184 Console.WriteLine("接收 " + nReadSize + " 字节");
185
186 TotleSize += nReadSize;
187 Console.WriteLine("接受总数为" + TotleSize);
188 }
189
190 file.Close();
191
192 string sendStr = "Ok!Sucess!";
193 byte[] bs = Encoding.ASCII.GetBytes(sendStr);
194 ss1.Send(bs, bs.Length, 0);
195 ss1.Shutdown(SocketShutdown.Both);
196
197 ss1.Close();
198
199 }
200
201 }
202 }
203
204 }
205 catch (SocketException e)
206 {
207 Console.WriteLine("{0}", e);
208 }
209 }
210 }



转载于:https://www.cnblogs.com/-ShiL/archive/2012/03/19/Star_201203192154.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值