只能找到当初的代码了。。控件看着代码搭配就好了(lll¬ω¬)
using System;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using System.Windows.Forms;
namespace _广播_
{
public partial class Form1 : Form
{
UdpClient udp;
private const int port = 9999;
private volatile bool IsStop = true;
public delegate void AddMessage(string str);
public void AddString(string str)
{
listBox1.Items.Add(str);
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
udp = new UdpClient(port);
Thread d = new Thread(ReceiveData);
IsStop = false;
d.IsBackground = true;
d.Start();
}
catch
{
MessageBox.Show("绑定错误!");
Close();
}
}
public void ReceiveData()
{
AddMessage a = new AddMessage(AddString);
while(!IsStop)
{
try
{
IPEndPoint remote = new IPEndPoint(IPAddress.Broadcast, 0);
byte[] bys = udp.Receive(ref remote);
string s = textBox1.Text + ":" + port;
if (s != remote.ToString())
{
string message = remote.ToString() + "说:" + Encoding.GetEncoding("gb2312").GetString(bys);
listBox1.Invoke(a, message);
}
}
catch
{
}
}
}
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Button1_Click(object sender, EventArgs e)
{
if(richTextBox1.Text != "")
{
byte[] bys = Encoding.GetEncoding("gb2312").GetBytes(richTextBox1.Text);
udp.Send(bys, bys.Length, new IPEndPoint(IPAddress.Broadcast, port));
// listBox1.Items.Add("我说:" + richTextBox1.Text);
richTextBox1.Clear();
}else
{
MessageBox.Show("请输入内容!");
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
IsStop = true;
Thread.Sleep(1000);
if (udp != null)
udp.Close();
}
private void Button2_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
}
}
|