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

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

时间:2014-05-31 14:26:40      阅读:446      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

这里是发送的代码:

SendVarData是转码后发送函数
bubuko.com,布布扣
 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             try
25             {
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         }  
bubuko.com,布布扣

以下是接收代码:

ReceiveVarData是接收后转码
bubuko.com,布布扣
 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                 else
51                 {
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        }
bubuko.com,布布扣

 

C#Socket文件传输(发送与接收代码),布布扣,bubuko.com

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

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/reynoldchan/p/3762014.html

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