//********************接收端*********************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Socket广播
{
public partial class Form1 : Form
{
private IPEndPoint enLoacp;
private Socket mySocket;
private Thread Mythread;
private EndPoint ep;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
enLoacp = new IPEndPoint(IPAddress.Any, 9050);
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
mySocket.Bind(enLoacp);
ep = (EndPoint)enLoacp;
Mythread = new Thread(new ThreadStart(Recive));
Mythread.Name = "a";
Mythread.Start();
}
private void Recive()
{
try
{
while (true)
{
try
{
if (mySocket == null)
{
Thread.Sleep(1000);
continue;
}
else
{
if (listBox1.Items.Count > 10)
{
listBox1.Items.Clear();
}
byte[] b=new byte[1024];
int size = mySocket.ReceiveFrom(b,ref ep);
string strbuff = Encoding.Default.GetString(b,0,size);
listBox1.Items.Add("收到广播消息:" + strbuff);
//**************发送端********************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Socket广播发送端
{
public partial class Form1 : Form
{
private IPEndPoint enLoacp;
private Socket mySocket;
private Thread Mythread;
private byte[] sendbuff;
public Form1()
{
InitializeComponent();
}