using PublicCode; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace broadcast2 { public partial class broadcast2 : Form { IPAddress IP = null; EndPoint SendEP = null; Socket sock = null; private string logfile = ""; private int index = 0; private Thread rcvThread = null; public broadcast2() { InitializeComponent(); StartPosition = FormStartPosition.CenterScreen; sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sock.EnableBroadcast = true; textBox2.Text = this.Handle.ToString(); logfile = Path.Combine(Application.StartupPath, "logs.txt"); this.Text = "发送者"; } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == 0x04A) { COPYDATASTRUCT cdata = new COPYDATASTRUCT(); Type mytype = cdata.GetType(); cdata = (COPYDATASTRUCT)m.GetLParam(mytype); MessageBox.Show(cdata.lpData); } if (m.Msg == 1025) { string text = ""; PublicUtils.GlobalGetAtomName(m.LParam.ToInt32(), text, 1024); MessageBox.Show(text); } } private void button2_Click(object sender, EventArgs e) { //PublicUtils.SendFormMsg_Copydata(PublicUtils.FindWindow("TForm2", "Form2"), "xxx 暗室逢灯12345 54321"); PublicUtils.SendFormMsg(PublicUtils.FindWindow("TForm2", "Form2"), "xxx 暗室逢灯12345 54321--"); } private void Send() { //byte[] sendbuf = Encoding.UTF8.GetBytes(string.Format("消息 {0}", ++index)); byte[] sendbuf = Encoding.UTF8.GetBytes(DateTime.Now.ToString("HHmmss")); sock.SendTo(sendbuf, SendEP); //Console.WriteLine(string.Format("{0} 发送广播消息 {1}", DateTime.Now.ToString("HH:mm:ss.fff"), i)); writeLog(string.Format("{0} 发送广播消息 {1}", DateTime.Now.ToString("HH:mm:ss.fff"), DateTime.Now.ToString("HHmmss"))); //byte[] receiveBuf = new byte[1000]; //sock.Receive(receiveBuf); //string msg = Encoding.UTF8.GetString(receiveBuf, 0, receiveBuf.Length); ////Console.WriteLine(string.Format("{0} 收到回复: {0}", DateTime.Now.ToString("HH:mm:ss.fff"), msg); //writeLog(string.Format("{0} 收到回复: {1}", DateTime.Now.ToString("HH:mm:ss.fff"), msg)); } private void writeLog(string text) { using (StreamWriter sw = new StreamWriter(logfile, true, Encoding.UTF8)) { sw.WriteLine(text); } } private void button1_Click(object sender, EventArgs e) { index = 0; if (!timer1.Enabled) { IP = IPAddress.Parse(textBox1.Text.Trim()); SendEP = new IPEndPoint(IP, 11000); timer1.Start(); button1.Text = "停止"; textBox1.Enabled = false; rcvThread = new Thread(new ThreadStart(DoReceive)); rcvThread.IsBackground = true; rcvThread.Start(); } else { timer1.Stop(); button1.Text = "开始"; textBox1.Enabled = true; if (rcvThread != null) { rcvThread.Abort(); rcvThread = null; } } } /// <summary> /// 方式一:阻塞接收的方式 /// </summary> private void DoReceive() { while (true) { try { byte[] receiveBuf = new byte[2048]; sock.Receive(receiveBuf); string msg = Encoding.UTF8.GetString(receiveBuf, 0, receiveBuf.Length); //Console.WriteLine(string.Format("{0} 收到回复: {0}", DateTime.Now.ToString("HH:mm:ss.fff"), msg); string stext = string.Format("{0} 收到:{1}", DateTime.Now.ToString("HH:mm:ss.fff"), msg).Replace('\0', ' ').Trim(); writeLog(stext); } catch { } } } /// <summary> /// 方式二:监听方式,这种方式不行 /// </summary> private void DoReceive2() { UdpClient listener = new UdpClient(); IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 11001); listener.ExclusiveAddressUse = false; listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); listener.Client.Bind(endPoint); while (true) { byte[] receiveBuf = listener.Receive(ref endPoint); string msg = Encoding.UTF8.GetString(receiveBuf, 0, receiveBuf.Length); string stext = string.Format("{0}收到:{1}", DateTime.Now.ToString("HH:mm:ss.fff"), msg).Replace('\0', ' ').Trim(); writeLog(stext); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { timer1.Stop(); Application.Exit(); } private void timer1_Tick(object sender, EventArgs e) { Send(); } public static void UdpServer(IPEndPoint serverIP) { bool thread_flag = true; Console.WriteLine("UDP服务器开始监听" + serverIP.Port + "端口"); Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpServer.Bind(serverIP); IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 11000); EndPoint Remote = (EndPoint)ipep; new Thread(() => { while (thread_flag) { byte[] data = new byte[1024]; int length = 0; try { length = udpServer.ReceiveFrom(data, ref Remote);//接受来自服务器的数据 } catch (Exception ex) { Console.WriteLine(string.Format("出现异常:{0}", ex.Message)); break; } string datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string message = Encoding.UTF8.GetString(data, 0, length); string ipport = (Remote as IPEndPoint).Address.ToString() + ":" + (Remote as IPEndPoint).Port.ToString(); Console.WriteLine(string.Format("{0} 收到來自{1}的消息:{2}", datetime, ipport, message)); } udpServer.Close(); }).Start(); } } }
公用单元文件:
PublicUtils.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace PublicCode { public static class PublicUtils { public const int WM_TextNotify = 1025; [DllImport("User32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hwnd, int msg, int wParam, ref COPYDATASTRUCT IParam); [DllImport("user32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage2(int hwnd, int wMsg, int wParam, int lParam); [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] public static extern int GlobalAddAtom(string lpString); [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] public static extern int GlobalDeleteAtom(int atom); [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] public static extern uint GlobalGetAtomName(int nAtom, string lpBuffer, int nSize); public static void SendFormMsg_Copydata(IntPtr handle, string atext) { byte[] arr = Encoding.Unicode.GetBytes(atext); int len = arr.Length; COPYDATASTRUCT cdata; cdata.dwData = (IntPtr)100; cdata.lpData = atext; cdata.cData = len + 1; SendMessage(handle, 0x04A, 0, ref cdata); } public static void SendFormMsg(IntPtr handle, string atext) { int atom = GlobalAddAtom(atext); SendMessage2((int)handle, WM_TextNotify, 0, atom); GlobalDeleteAtom(atom); } } public struct COPYDATASTRUCT { public IntPtr dwData; public int cData; [MarshalAs(UnmanagedType.LPWStr)] public string lpData; } }
更正:
IntPtr stext = Marshal.AllocHGlobal(1024); if (m.Msg == 1025) { PublicUtils.GlobalGetAtomName(m.LParam.ToInt32(), stext, 1024); textBox3.Text = Marshal.PtrToStringUni(stext); Marshal.FreeHGlobal(stext); }
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] public static extern uint GlobalGetAtomName(int nAtom, IntPtr lpBuffer, int nSize);