----紧急求救,关于udp的广播的问题,有代码和注释,我的程序就是不能发送和接收,也不能干净的退出去,不知道为什么?----
whmjw 2005-07-10 11:39:13 private System.Windows.Forms.RichTextBox rtfSend;//发送的字符串发在里面
private System.Windows.Forms.Splitter splitter;
private System.Windows.Forms.RichTextBox rtfReceive;/接收到的字符串发在里面
private System.Windows.Forms.Button btnSend;
//定义一个线程
private Thread thread;
private static readonly IPAddress GroupAddress = IPAddress.Parse("224.0.0.1");
private const int GroupPort = 11000;
public mainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
//开启一个线程来监听
thread = new Thread(new ThreadStart(StartListener));
thread.Start();
}
//监听什么都收不到
private void StartListener()
{
bool done = false;
UdpClient listener = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort);
try
{
listener.JoinMulticastGroup(GroupAddress);
listener.Connect(groupEP);
while (!done)
{
byte[] bytes = listener.Receive( ref groupEP);
//接收字符串
rtfReceive.Text=Encoding.ASCII.GetString(bytes,0,bytes.Length);
}
listener.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void Send( String message)
{
UdpClient sender = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort);
try
{
byte[] bytes = Encoding.ASCII.GetBytes(message);
sender.Send(bytes, bytes.Length, groupEP);
sender.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//发送处理
private void btnSend_Click(object sender, System.EventArgs e)
{
Send(this.rtfSend.Text);
}
//程序退出,关闭线程, 但问题是程序不能干净的退出去,
//在任务管理器中也还是可以看的到,如果加上thread.join();程序会是在无响应状态
//另外我看过微软的Quickstart的那个例子,它是控制台的,在控件台下我可以照它的例子可以调通,我把它转为Winform的就是不能通过???
//我在Csdn上查过这方面的资料,都不行,郁闷呀
private void mainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
thread.Abort();
}
//另外问一个问题,如果是广播的形式,是不是在子网内任何一台机器用了我的程序,发送了字符串,则同一个子网内的所有的机器都会收到,我的程序的环境是用到我们程序的,大概也就是10多台电脑,但还有一百多台机器是不用我们的程序,如果我采用广播的这种形式会不会太占用带宽,
如果采用多播,组播是否可以更好的解决这个问题
以前没有接触地网络编程,见笑了:)