using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets;
namespace Dachie { class Program { static void Main(string[] args) { } } public class MessageUtility {
//缺省端口号 private const int DEFAULT_PORT = 49967;
private MessageUtility() { // // TODO: 在此处添加构造函数逻辑 // }
//发送消息方法 public static void SendMessage(string msg) { byte[] data = new byte[1024]; //本机主机信息 IPHostEntry host = Dns.GetHostByName(Dns.GetHostName());
//端口号参数以后重构时可以做成一个方法从配置文件中读取端口号 IPEndPoint ipep = new IPEndPoint(host.AddressList[0], DEFAULT_PORT);
//创建一个udp套接字 Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
if (msg.Length != 0) { data = Encoding.Unicode.GetBytes(msg); try { server.SendTo(data, data.Length, SocketFlags.None, ipep); } catch (SocketException) { } finally { server.Close(); }
}
}
//接受消息方法 public static string ReceiveMessage() { int recv; byte[] data = new byte[1024];
//创建一个随机终结点对象 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, DEFAULT_PORT);
//创建一个Udp套接字 Socket newsock = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//将随机终结点与Udp套接字绑定,以等待流入的数据包 newsock.Bind(ipep);
//创建一个接受任意发送者的终结点 IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint tmpRemote = (EndPoint)(sender);
try { recv = newsock.ReceiveFrom(data, ref tmpRemote); return Encoding.Unicode.GetString(data, 0, data.Length); } catch (SocketException) { return null; } finally { newsock.Close();//关闭套接字释放资源 }
}
} }
|
请发表评论