代码语言:javascript复制
1 public class SocketHelper
2 {
3 /// <summary>
4 /// 功能描述:得到一个实例对象
5 /// </summary>
6 /// <returns>SocketHelper</returns>
7 public static SocketHelper GetSocketHelper()
8 {
9 try
10 {
11 return new SocketHelper();
12 }
13 catch
14 {
15 throw;
16 }
17 }
18 /// <summary>
19 /// 委托
20 /// </summary>
21 /// <param name="intport">intport</param>
22 /// <param name="strmsg">strmsg</param>
23 public delegate void RecvGBDelegate(int intport, string strmsg);
24 /// <summary>
25 /// 监听到广播事件
26 /// </summary>
27 public event RecvGBDelegate OnRecvGBMessageChanged;
28
29 /// <summary>
30 /// 功能描述:监听广播,使用线程调用
31 /// 作 者:huangzh
32 /// 创建日期:2015-08-17 10:28:19
33 /// 任务编号:
34 /// </summary>
35 /// <param name="objport">监听端口</param>
36 public void RecvUDPGB(object objport)
37 {
38 UdpClient client = null;
39 try
40 {
41 if (!(objport is int))
42 {
43 throw new Exception("参数不是int类型");
44 }
45 int intport = Convert.ToInt32(objport);
46 client = new UdpClient(new IPEndPoint(IPAddress.Any, intport));
47 IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
48 while (true)
49 {
50 byte[] buf = client.Receive(ref endpoint);
51 string strmsg = Encoding.UTF8.GetString(buf);
52 if (strmsg.IndexOf("CloseClient") >= 0)
53 break;
54 OnRecvGBMessageChanged(intport, strmsg);
55 }
56 }
57 catch
58 {
59 throw;
60 }
61 finally
62 {
63 if (client != null)
64 client.Close();
65 }
66 }
67
68 /// <summary>
69 /// 功能描述:发送广播
70 /// </summary>
71 /// <param name="strmsg">strmsg</param>
72 /// <param name="intport">intport</param>
73 public void SendUDPGB(string strmsg, int intport)
74 {
75 try
76 {
77 SendUDPGB(Encoding.UTF8.GetBytes(strmsg), intport);
78 }
79 catch
80 {
81 throw;
82 }
83 }
84
85 /// <summary>
86 /// 功能描述:发送广播
87 /// </summary>
88 /// <param name="buf">buf</param>
89 /// <param name="intport">intport</param>
90 public void SendUDPGB(byte[] buf, int intport)
91 {
92 UdpClient client = null;
93 try
94 {
95 client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
96 IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), intport);
97 client.Send(buf, buf.Length, endpoint);
98
99 }
100 catch
101 {
102 throw;
103 }
104 finally
105 {
106 if (client != null)
107 {
108 client.Close();
109 }
110 }
111 }
112
113
114 /// <summary>
115 /// 功能描述:接收文件
116 /// </summary>
117 /// <param name="intport">intport</param>
118 /// <param name="strApplicationPath">strApplicationPath</param>
119 /// <returns>返回值</returns>
120 public bool RecvFile(int intport, string strApplicationPath)
121 {
122 Socket server = null;
123 Socket client = null;
124 try
125 {
126 //创建一个网络端点
127 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, intport);
128
129 //创建一个套接字
130 server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
131
132 //绑定套接字到端口
133 server.Bind(ipep);
134
135 //开始侦听(并堵塞该线程)
136 server.Listen(10);
137
138 //确认连接
139 client = server.Accept();
140
141 //获得客户端节点对象
142 IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
143
144 //获得[文件名]
145 string strSendFileName = System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client));
146 //获得[保存位置]
147 string strSavePath = System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client));
148 strSendFileName = strApplicationPath "\" (string.IsNullOrEmpty(strSavePath) ? "" : (strSavePath "\")) strSendFileName;
149 string strdir = Path.GetDirectoryName(strSendFileName);
150 if (!Directory.Exists(strdir))
151 {
152 Directory.CreateDirectory(strdir);
153 }
154 //获得[包的大小]
155 string strbagSize = System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client));
156 //MessageBox.Show("包大小" bagSize);
157
158 //获得[包的总数量]
159 int intbagCount = int.Parse(System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client)));
160 //MessageBox.Show("包的总数量" bagCount);
161
162 //获得[最后一个包的大小]
163 string strbagLast = System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client));
164 //MessageBox.Show("最后一个包的大小" bagLast);
165
166 //创建一个新文件
167 using (FileStream myFileStream = new FileStream(strSendFileName, FileMode.Create, FileAccess.Write))
168 {
169 //已发送包的个数
170 int intSendedCount = 0;
171
172 while (true)
173 {
174 byte[] data = TransferFiles.ReceiveVarData(client);
175 if (data.Length == 0)
176 {
177 break;
178 }
179 else
180 {
181 intSendedCount ;
182 //将接收到的数据包写入到文件流对象
183 myFileStream.Write(data, 0, data.Length);
184 //显示已发送包的个数
185 //MessageBox.Show("已发送包个数" SendedCount.ToString());
186 }
187 }
188 }
189 }
190 catch
191 {
192 throw;
193 }
194 finally
195 {
196 //关闭套接字
197 if (client != null)
198 client.Close();
199 if (server != null)
200 server.Close();
201
202 }
203 return true;
204 }
205
206
207 /// <summary>
208 /// 功能描述:发送文件
209 /// </summary>
210 /// <param name="strfile">文件路径</param>
211 /// <param name="strDirName">发布相对位置</param>
212 /// <param name="toip">目标ip</param>
213 /// <param name="inttoPort">目标端口</param>
214 public void SendFile(
215 string strfile,
216 string strDirName,
217 IPAddress toip,
218 int inttoPort)
219 {
220 Socket client = null;
221 try
222 {
223 //创建一个文件对象
224 FileInfo ezoneFile = new FileInfo(strfile);
225 //打开文件流
226 using (FileStream ezoneStream = ezoneFile.OpenRead())
227 {
228 //包的大小
229 int intPacketSize = 50000;
230 //包的数量
231 int intPacketCount = (int)(ezoneStream.Length / ((long)intPacketSize));
232 //this.textBox8.Text=PacketCount.ToString();
233 //this.progressBar1.Maximum=PacketCount;
234 //最后一个包的大小
235 int intLastDataPacket = (int)(ezoneStream.Length - ((long)(intPacketSize * intPacketCount)));
236
237
238 //指向远程服务端节点
239 IPEndPoint ipep = new IPEndPoint(toip, inttoPort);
240 //创建套接字
241 client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
242 //连接到发送端
243 client.Connect(ipep);
244
245 //获得客户端节点对象
246 IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
247 //获得客户端的IP地址
248 //this.textBox7.Text=clientep.Address.ToString();
249 //发送[文件名]到客户端
250 TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(ezoneFile.Name));
251 //发送[保存位置]到客户端
252 strDirName = strDirName.Trim(new char[] { '\' });
253 TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(strDirName));
254 //发送[包的大小]到客户端
255 TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(intPacketSize.ToString()));
256 //发送[包的总数量]到客户端
257 TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(intPacketCount.ToString()));
258 //发送[最后一个包的大小]到客户端
259 TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(intLastDataPacket.ToString()));
260
261 //数据包
262 byte[] data = new byte[intPacketSize];
263 //开始循环发送数据包
264 for (int i = 0; i < intPacketCount; i )
265 {
266 //从文件流读取数据并填充数据包
267 ezoneStream.Read(data, 0, data.Length);
268 //发送数据包
269 TransferFiles.SendVarData(client, data);
270 ////显示发送数据包的个数
271 //this.textBox10.Text=((int)(i 1)).ToString();
272 ////进度条值的显示
273 //this.progressBar1.PerformStep();
274 }
275
276 //如果还有多余的数据包,则应该发送完毕!
277 if (intLastDataPacket != 0)
278 {
279 data = new byte[intLastDataPacket];
280 ezoneStream.Read(data, 0, data.Length);
281 TransferFiles.SendVarData(client, data);
282 // this.progressBar1.Value=this.progressBar1.Maximum;
283 }
284 }
285 }
286 catch
287 {
288 throw;
289 }
290 finally
291 {
292 if (client != null)
293 client.Close();
294 }
295 }
296
297 /// <summary>
298 /// 功能描述:发送信息
299 /// </summary>
300 /// <param name="ip">ip</param>
301 /// <param name="intport">intport</param>
302 /// <param name="strmsg">msg</param>
303 public void SendMsg(
304 IPAddress ip,
305 int intport,
306 string strmsg)
307 {
308 UdpClient uc = null;
309 try
310 {
311 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strmsg);
312 uc = new UdpClient();
313 uc.Send(bytes, bytes.Length, ip.ToString(), intport);
314
315 }
316 catch
317 {
318 throw;
319 }
320 finally
321 {
322 if (uc != null)
323 {
324 uc.Close();
325 }
326 }
327 }
328 /// <summary>
329 /// 监听委托
330 /// </summary>
331 /// <param name="strmsg">strmsg</param>
332 public delegate void RecvMsgDelegate(string strmsg);
333 /// <summary>
334 /// 监听事件
335 /// </summary>
336 public event RecvMsgDelegate OnRecvMsg;
337
338 /// <summary>
339 /// 功能描述:接收信息
340 /// </summary>
341 /// <param name="objport">objport</param>
342 public void RecvMsg(object objport)
343 {
344 if (!(objport is int))
345 {
346 throw new Exception("参数不是int类型");
347 }
348 int intport = Convert.ToInt32(objport);
349 UdpClient uc = null;
350 try
351 {
352 uc = new UdpClient(intport);
353 IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
354 while (true)
355 {
356 string strtext = System.Text.Encoding.UTF8.GetString(uc.Receive(ref iep));
357 if (strtext == "Close")
358 break;
359 OnRecvMsg(strtext);
360 }
361 uc.Close();
362 }
363 catch
364 {
365 throw;
366 }
367 finally
368 {
369 if (uc != null)
370 {
371 uc.Close();
372 }
373 }
374 }
375
376
377 public IPAddress GetThisIPAddress()
378 {
379 try
380 {
381 string strhostName = Dns.GetHostName();
382 IPAddress[] addressList = Dns.GetHostAddresses(strhostName);
383 IPAddress thisIp = null;
384 foreach (IPAddress item in addressList)
385 {
386 if (item.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
387 {
388 thisIp = item;
389 break;
390 }
391 }
392 return thisIp;
393 }
394 catch
395 {
396 throw;
397 }
398 }
399 }
代码语言:javascript复制 1 public class TransferFiles
2 {
3 /// <summary>
4 /// 功能描述:发送数据
5 /// </summary>
6 /// <param name="s">s</param>
7 /// <param name="data">data</param>
8 /// <returns>返回值</returns>
9 public static int SendData(Socket s, byte[] data)
10 {
11 int inttotal = 0;
12 int intsize = data.Length;
13 int intdataleft = intsize;
14 int intsent;
15
16 while (inttotal < intsize)
17 {
18 intsent = s.Send(data, inttotal, intdataleft, SocketFlags.None);
19 inttotal = intsent;
20 intdataleft -= intsent;
21 }
22
23 return inttotal;
24 }
25
26 /// <summary>
27 /// 功能描述:接收数据
28 /// </summary>
29 /// <param name="s">s</param>
30 /// <param name="intsize">size</param>
31 /// <returns>返回值</returns>
32 public static byte[] ReceiveData(Socket s, int intsize)
33 {
34 int inttotal = 0;
35 int intdataleft = intsize;
36 byte[] data = new byte[intsize];
37 int intrecv;
38 while (inttotal < intsize)
39 {
40 intrecv = s.Receive(data, inttotal, intdataleft, SocketFlags.None);
41 if (intrecv == 0)
42 {
43 data = null;
44 break;
45 }
46
47 inttotal = intrecv;
48 intdataleft -= intrecv;
49 }
50 return data;
51 }
52
53 /// <summary>
54 /// 功能描述:发送数据
55 /// </summary>
56 /// <param name="s">s</param>
57 /// <param name="data">data</param>
58 /// <returns>返回值</returns>
59 public static int SendVarData(Socket s, byte[] data)
60 {
61 int inttotal = 0;
62 int intsize = data.Length;
63 int intdataleft = intsize;
64 int intsent;
65 byte[] datasize = new byte[4];
66 datasize = BitConverter.GetBytes(intsize);
67 intsent = s.Send(datasize);
68
69 while (inttotal < intsize)
70 {
71 intsent = s.Send(data, inttotal, intdataleft, SocketFlags.None);
72 inttotal = intsent;
73 intdataleft -= intsent;
74 }
75
76 return inttotal;
77 }
78
79 /// <summary>
80 /// 功能描述:接收数据
81 /// </summary>
82 /// <param name="s">s</param>
83 /// <returns>返回值</returns>
84 public static byte[] ReceiveVarData(Socket s)
85 {
86 int inttotal = 0;
87 int intrecv;
88 byte[] datasize = new byte[4];
89 intrecv = s.Receive(datasize, 0, 4, SocketFlags.None);
90 int intsize = BitConverter.ToInt32(datasize, 0);
91 int intdataleft = intsize;
92 byte[] data = new byte[intsize];
93 while (inttotal < intsize)
94 {
95 intrecv = s.Receive(data, inttotal, intdataleft, SocketFlags.None);
96 if (intrecv == 0)
97 {
98 data = null;
99 break;
100 }
101 inttotal = intrecv;
102 intdataleft -= intrecv;
103 }
104 return data;
105 }
106 }
包含了:广播,消息,发送文件等