资源预览内容
第1页 / 共8页
第2页 / 共8页
第3页 / 共8页
第4页 / 共8页
第5页 / 共8页
第6页 / 共8页
第7页 / 共8页
第8页 / 共8页
亲,该文档总共8页全部预览完了,如果喜欢就下载吧!
资源描述
using System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using System.Net;using System.Threading;using System.IO;namespace socketDemo class Client TcpClient client; long fileLength; BinaryReader reader; byte data = new byte8192; /准备工作 public Client(IPAddress serverIp) int port = 6000; int port1; int.TryParse(DateTime.Now.ToShortDateString().Replace(-, ).Substring(2), out port1); client = new TcpClient(); client.Connect(serverIp, port); Console.WriteLine(连上了); NetworkStream stream = client.GetStream(); reader = new BinaryReader(stream); /接收数据 public void recv() FileStream fs = File.Create(DateTime.Now.Ticks + .gif); byte fileLengthSrc = new byte8; try reader.Read(fileLengthSrc, 0, 8); long fileLength = getNum(fileLengthSrc); long reds = 0;/已经读取字节数 /开始传输 while (reds data.Length) int red = reader.Read(data, 0, data.Length); if (red = 0) break; fs.Write(data, 0, red); reds += red; else if (fileLength - reds 0) int red = reader.Read(data, 0, data.Length); if (red = 0) break; fs.Write(data, 0, red); reds += red; Thread.Sleep(10); catch (Exception ex) Console.WriteLine(数据传输异常或者服务端已离线: + ex.Message); fs.Flush(); fs.Close(); reader.Close(); client.Close(); static long getNum(byte bytes)/二进制转十进制(我帖子里留言那位兄弟滴代码很牛x _) /long型数据类型为字节 long num = 0; int n = Math.Min(bytes.Length, 4) - 1; for (int i = n; i -1; i-) num = (num 8) | bytesi;/num = (num 0) writer.Write(data, 0, reds); total += reds;
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号