***
```C#
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();
}
}
}
``` 用 UDP 去广播
呃呃呃,用线程去执行这个操作 ZeroMQ了解一下 多谢!!学习中!! 用socket写,很简单的。 本帖最后由 fabulousElena 于 2020-8-18 18:34 编辑
lizf2020 发表于 2020-8-18 17:39
大佬可否指点写代码
https://cdn.jsdelivr.net/gh/fabulousElena/PicGo/file/ChatDemoWithSocket.7z
这是之前写的源码。。你改一下就可以变成你需要的了。
页:
[1]
2