Socket通讯之UDP
发送消息的类:
/// <summary> /// 发送消息 /// </summary> public class UdpSendMessage { System.Net.Sockets.UdpClient udpClient = null; public static int BufferSize = 1024; public UdpSendMessage() { udpClient = new System.Net.Sockets.UdpClient(); } /// <summary> /// 发送Socket消息 /// </summary> /// <param name="ip">远程IP</param> /// <param name="port">远程端口号</param> /// <param name="datagram">数据包</param> private void Send(string ip, int port, byte[] datagram) { // System.Net.IPEndPoint endPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port); if (datagram.Length > BufferSize) { for (int i = 0, srcOffset = 0; i < datagram.Length / BufferSize + 1; i++, srcOffset++) { if (i == datagram.Length / BufferSize) { byte[] dst = new byte[datagram.Length - BufferSize * i]; Buffer.BlockCopy(datagram, srcOffset * BufferSize, dst, 0, datagram.Length - BufferSize * i); udpClient.BeginSend(dst, dst.Length, endPoint, new AsyncCallback(SendCallback), true); } else { byte[] dst = new byte[BufferSize]; Buffer.BlockCopy(datagram, srcOffset * BufferSize, dst, 0, BufferSize); udpClient.BeginSend(dst, dst.Length, endPoint, new AsyncCallback(SendCallback), false); } System.Threading.Thread.Sleep(1); } } else { udpClient.BeginSend(datagram, datagram.Length, endPoint, new AsyncCallback(SendCallback), true); } } private void SendCallback(IAsyncResult asynResult) { try { if ((bool)asynResult.AsyncState) { udpClient.EndSend(asynResult); } } catch (Exception ex) { throw ex; } } }
接收消息的类
/// <summary> /// 接收消息 /// </summary> public class UdpResiveMessage { System.Net.Sockets.UdpClient udpClient = null; StringBuilder sbResvieMsg = new StringBuilder(); /// <summary> /// 打开监听端 /// </summary> /// <param name="port">监听端口号</param> public void BeginListen(int port) { udpClient = new System.Net.Sockets.UdpClient(port, System.Net.Sockets.AddressFamily.InterNetwork); udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null); } private void ReceiveCallback(IAsyncResult asynResult) { try { IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); byte[] buffer = udpClient.EndReceive(asynResult, ref remoteEP); string ss = System.Text.Encoding.Default.GetString(buffer); if (!string.IsNullOrWhiteSpace(ss)) { sbResvieMsg.Append(ss); } if (buffer.Length < 1024) { MessageBox.Show(sbResvieMsg.ToString()); } udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null); } catch (Exception ex) { throw ex; } } }
测试代码:打开监听端:
UdpResiveMessage udpListen = new UdpResiveMessage(); udpListen.BeginListen(10003);
发送字符串
UdpSendMessage udpSend = new UdpSendMessage(); udpSend.Send("127.0.0.1", 10003, System.Text.Encoding.Default.GetBytes(this.textBox1.Text.Trim()));
发送文件
/// <summary> /// 将文件转换为字节流 /// </summary> /// <param name="sFilePath"></param> /// <returns></returns> public byte[] GetFileByte(string sFilePath) { try { if (!System.IO.File.Exists(sFilePath)) { return null; } else { FileStream fs = new FileStream(sFilePath, FileMode.Open, FileAccess.Read); byte[] buffur = new byte[fs.Length]; fs.Read(buffur, 0, (int)fs.Length); fs.Close(); return buffur; } } catch //(Exception ex) { return null; } } /// <summary> /// 发送文件 /// </summary> private void SendFile() { UdpSendMessage udpSend = new UdpSendMessage(); udpSend.Send("127.0.0.1", 10003, GetFileByte("d:\\BookOrder.pdf")); }