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 = ;
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 = ;
if (!timer1.Enabled)
{
IP = IPAddress.Parse(textBox1.Text.Trim());
SendEP = new IPEndPoint(IP, ); 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[];
sock.Receive(receiveBuf);
string msg = Encoding.UTF8.GetString(receiveBuf, , 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, );
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, , 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, );
EndPoint Remote = (EndPoint)ipep;
new Thread(() =>
{
while (thread_flag)
{
byte[] data = new byte[];
int length = ;
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, , 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 = ; [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);
cdata.lpData = atext;
cdata.cData = len + ;
SendMessage(handle, 0x04A, , ref cdata);
} public static void SendFormMsg(IntPtr handle, string atext)
{
int atom = GlobalAddAtom(atext);
SendMessage2((int)handle, WM_TextNotify, , 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 == )
{
PublicUtils.GlobalGetAtomName(m.LParam.ToInt32(), stext, );
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);

最新文章

  1. ASP.NET MVC 概述
  2. iOS学习——制作一个小型加法计算器
  3. Java基础之集合框架——使用集合Vector&lt;&gt;挑选演员(TryVector)
  4. Java自学成长路线(转载)
  5. linux makefle学习
  6. [转载]C宏定义的小结
  7. 详细:idea如何设置类头注释和方法注释
  8. bzoj 3864: Hero meet devil [dp套dp]
  9. BDD敏捷开发入门与实战
  10. [SDOI2009]HH的项链-树状数组/线段树
  11. Celery 1
  12. laravel5.5通过Migrations修改表 的artisan命令
  13. 1.1实战项目:电影周周看V1(初识小程序)
  14. 使用lld自动发现监控多实例redis
  15. angular笔记_6
  16. loadrunner&#160;场景设计-添加Unix、Linux&#160;Resources计数器
  17. 《DSP using MATLAB》Problem 5.27
  18. boot分区剩余空间不足
  19. ffmpeg开发基础知识
  20. Android studio 安装过程中遇到的问题

热门文章

  1. 牛顿迭代法--求任意数的开n次方
  2. SpringMVC——SSM整合
  3. web-pc项目中index页面分析
  4. awk及sum求和!
  5. request和response对象如何解决中文乱码问题?
  6. XML规范化(DTD)
  7. Day1-B-CF-1144B
  8. windows下pycharm连接vagrant的python环境
  9. 123、Java面向对象之引用传递实例一
  10. 六、Centos7中配置svn服务器