using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace UDPClient { public partial class Frm_Client : Form { Icon ico1 = new Icon("icon.ico"); Icon ico2 = new Icon("clear.ico"); bool is1; bool isTwinkle; static UdpClient client; static IPEndPoint endpoint; static System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer(); public Frm_Client() { InitializeComponent(); } private void Frm_Client_Load(object sender, EventArgs e) { client = new UdpClient(new IPEndPoint(IPAddress.Any, 25333)); endpoint = new IPEndPoint(IPAddress.Any, 0); //启动客户端监听 Thread t = new Thread(new ThreadStart(ClientThread)); t.Start(); //启动Web监听 Thread w = new Thread(new ThreadStart(WebListen)); w.Start(); //初始化Timer tmr.Interval = 390; tmr.Tick += tmr_Tick; tmr.Enabled = true; } void tmr_Tick(object sender, EventArgs e) { if (!isTwinkle) return; if (is1) { is1 = false; notifyIcon.Icon = ico2; } else { is1 = true; notifyIcon.Icon = ico1; } } public static IPAddress GetHostIP() { string strHostName = Dns.GetHostName(); //得到本机的主机名 IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); //取得本机IP foreach (var item in ipEntry.AddressList) { if (!item.IsIPv6LinkLocal) { return item; } } return null; } private static void WebListen() { try { HttpListener listerner = new HttpListener(); listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问 listerner.Prefixes.Add("http://127.0.0.1:25330/web/"); listerner.Start(); Console.WriteLine("WebServer Start Successed......."); while (true) { //等待请求连接 //没有请求则GetContext处于阻塞状态 HttpListenerContext ctx = listerner.GetContext(); ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码 string username = ctx.Request.QueryString["username"]; if (username != null && username.Length > 0) { IPAddress addr = GetHostIP(); string str = username + " " + (addr == null ? "null" : addr.ToString()) + " 25333"; Console.WriteLine(str); byte[] buf = Encoding.Default.GetBytes(str); client.Send(buf, buf.Length, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25433)); } ctx.Response.Close(); } } catch (Exception e) { Console.WriteLine(e.Message); } } private void ClientThread() { try { Console.WriteLine("客户端开始监听..."); while (true) { byte[] buf = client.Receive(ref endpoint); string msg = Encoding.Default.GetString(buf); Console.WriteLine("收到数据: " + msg); isTwinkle = true; notifyIcon.ShowBalloonTip(1000,"四喜消息提示","您有新的提醒 请注意查收!",ToolTipIcon.Info); } } catch (Exception e) { Console.WriteLine(e.Message); client.Close(); } } private void button2_Click(object sender, EventArgs e) { isTwinkle = !isTwinkle; } private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) { isTwinkle = false; notifyIcon.Icon = ico1; } } }