打开APP
userphoto
未登录

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

开通VIP
C#Socket文件传输(发送与接收代码)
userphoto

2017.03.12

关注

这里是发送的代码:

SendVarData是转码后发送函数
 1 /// <summary> 2         /// 发送文件 3         /// </summary> 4         /// <param name="userName"></param> 5         private void SendFileToClient(string userName) 6         { 7             User targetUser = userListDict[userName]; 8             String targetUserIP = "127.0.0.1"; 9 10             FileInfo EzoneFile = new FileInfo(sendFilePath);11             FileStream EzoneStream = EzoneFile.OpenRead();12             //包的大小13             int packetSize = 1000;14             //包的数量15             int packetCount = (int)(EzoneFile.Length / ((long)packetSize));16 17             //最后一个包的大小18             int lastPacketData = (int)(EzoneFile.Length-((long)packetSize*packetCount));19 20             byte[] data = new byte[packetSize];21 22             23 24             try25             {26                 IPHostEntry ipHost = Dns.GetHostEntry(targetUserIP);27                 IPAddress ipAdd = ipHost.AddressList[0];28                 IPEndPoint ipEndP = new IPEndPoint(ipAdd, targetUser.userPort);29 30                 Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);31                 client.Connect(ipEndP);32                 //发送本机昵称33                 FormClient.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(localNickName));34                 //发送包的大小35                 FormClient.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(packetSize.ToString()));36                 //发送包的总数量37                 FormClient.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(packetCount.ToString()));38                 //client.SendFile(sendFilePath);39                 for (int i = 0; i < packetCount;i++ )40                 {41                     EzoneStream.Read(data, 0, data.Length);42                     FormClient.SendVarData(client,data);43                     AddReceiveFileInfo(userDialogDict[userName], packetCount.ToString() + "/" + i.ToString());44                 }45                 if (lastPacketData!=0)46                 {47                     data=new byte[lastPacketData];48                     EzoneStream.Read(data, 0, data.Length);49                     FormClient.SendVarData(client, data);50                 }51                 AddReceiveFileInfo(userDialogDict[userName], "传输完成!");52 53                 client.Shutdown(SocketShutdown.Both);54                 client.Close();55                 56             }57             catch (System.Exception ex)58             {59                 60             }61         }62         public static int SendVarData(Socket s, byte[] data)63         {64             int total = 0;65             int size = data.Length;66             int dataleft = size;67             int sent;68             byte[] datasize = new byte[4];69             datasize = BitConverter.GetBytes(size);70             sent = s.Send(datasize);71 72             while (total < size)73             {74                 sent = s.Send(data, total, dataleft, SocketFlags.None);75                 total += sent;76                 dataleft -= sent;77             }78 79             return total;80         }  

以下是接收代码:

ReceiveVarData是接收后转码
 1 /// <summary> 2         /// 接受其他客户端的文件 3         /// </summary> 4         private void ReceiveClientFile() 5         { 6             while (true) 7             { 8                  9                 Socket clientsocket = serverSocket.Accept();10                 Thread receiveThread = new Thread(ReceiveClientFileData);11                 receiveThread.Start(clientsocket);12                 receiveThread.IsBackground = true;13             }14             15         }16 17         private void ReceiveClientFileData(object clientSocket)18         {19             Socket myClientSocket = (Socket)clientSocket;20             string totalSize;//文件大小21             int totalCount = 0;//总的包数量22             int receiveCount = 0;//统计已收的包的数量23             string sendClientName;24             25             if (File.Exists(receiveFilePath))26             {27                 File.Delete(receiveFilePath);28             }29 30             FileStream fs = new FileStream(receiveFilePath, FileMode.Create,FileAccess.Write);31             //发送端的用户名字,用于确定对话框32             sendClientName = System.Text.Encoding.Unicode.GetString(FormClient.ReceiveVarData(myClientSocket));33             //文件大小34             totalSize = System.Text.Encoding.Unicode.GetString(FormClient.ReceiveVarData(myClientSocket));35             //总的包数量36             totalCount = int.Parse(System.Text.Encoding.Unicode.GetString(FormClient.ReceiveVarData(myClientSocket)));37 38             AddReceiveFileInfo(userDialogDict[sendClientName],receiveCount + "/" + totalSize);39             while (true)40             {41                 byte[] data = FormClient.ReceiveVarData(myClientSocket);42                 //接收来自socket的数据43 44                 if (data.Length==0)45                 {46                     AddReceiveFileInfo(userDialogDict[sendClientName], "接收完成!");47                     fs.Write(data, 0, data.Length);48                     break;49                 }50                 else51                 {52                     receiveCount++;53                     AddReceiveFileInfo(userDialogDict[sendClientName], receiveCount + "/" + totalSize);54                     fs.Write(data,0,data.Length);55                 }56 57                 58             }59             fs.Close();60             myClientSocket.Close();61 62         }63 64         private static byte[] ReceiveVarData(Socket s)  65        {  66            int total = 0;  67            int recv;  68            byte[] datasize = new byte[4];  69            recv = s.Receive(datasize, 0, 4, SocketFlags.None);  70            int size = BitConverter.ToInt32(datasize, 0);  71            int dataleft = size;  72            byte[] data = new byte[size];  73            while (total < size)  74            {  75                recv = s.Receive(data, total, dataleft, SocketFlags.None);  76                if (recv == 0)  77                {  78                    data = null;  79                    break;  80                }  81                total += recv;  82                dataleft -= recv;  83            }  84            return data;  85        }

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
用TCP/IP实现自己简单的应用程序协议:成帧器部分
C#之Socket操作类实例解析
在Android上使用LocalSocket实现上层Java和底层C++的通信
C++中实现ping功能2
手机网络游戏应用协议设计(二)
Android中Parcel的分析以及使用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服