文章中的StriveEngine.dll版本为V3.9.0.0,源码下载请到 这里
UDP比TCP通信,就相对简单多了
先上代码,建立2个控制台程序,分别为SEUDP1,SEUDP2,其中SEUDP1中增加一个类
class UDP { private IUdpEngine udpServerEngine; public UDP(int port) { this.udpServerEngine = NetworkEngineFactory.CreateUdpEngine(); this.udpServerEngine.Port = port; this.udpServerEngine.LogFilePath = @"C:\"; this.udpServerEngine.MessageReceived += udpServerEngine_MessageReceived; } private void udpServerEngine_MessageReceived(IPEndPoint obj1, byte[] obj2) { string msg = System.Text.Encoding.UTF8.GetString(obj2); Console.WriteLine("Get message from [{0}]:{1}", obj1.ToString(), msg); } public void Start() { this.udpServerEngine.Initialize(); } public void Send(string ip, int port, byte[] msg) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip), port); this. udpServerEngine.SendMessage(iep, msg); } public void Send(string ip, int port, string msg) { byte[] bs = System.Text.Encoding.UTF8.GetBytes(msg); this.Send(ip, port, bs); } }
同时,在SEUPD2中增加这个类的链接,然后就都可以使用了
SEUPD1中的Main函数
static void Main(string[] args) { UDP sender = ); sender.Start(); while (true) { string msg = Console.ReadLine(); sender.Send(, msg); } }
SEUPD2中的Main函数
static void Main(string[] args) { UDP sender = ); sender.Start(); while (true) { string msg = Console.ReadLine(); sender.Send(, msg); } }
启动SEUPD1和SEUDP2,在控制台敲任意字符,都能发送到对方,并且打印出来.
注意:
- UDP是没有客户端和服务端之分的,这一点和tcp的区别最明显
- 对报文没有那么多控制,(我说的控制,不是因为我没定义报文类,)
- 非面向连接,发送就完成,不管身后事