----紧急求救,关于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多台电脑,但还有一百多台机器是不用我们的程序,如果我采用广播的这种形式会不会太占用带宽,
如果采用多播,组播是否可以更好的解决这个问题

以前没有接触地网络编程,见笑了:)
...全文
206 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
whmjw 2005-07-10
  • 打赏
  • 举报
回复
昏呀,怎么没有人来呢??
JzeroBiao 2005-07-10
  • 打赏
  • 举报
回复
帮你顶..
wangrhliuyh 2005-07-10
  • 打赏
  • 举报
回复
关注,帮你顶
wangsaokui 2005-07-10
  • 打赏
  • 举报
回复
你可以在接收的时候做一个检测,比如一个特殊的ASCII码字符,如收到就结束,然后在你想结束的时候发送这个字符,自己结束自己。

没有看见这个帖子
whmjw 2005-07-10
  • 打赏
  • 举报
回复
沉的也太快了吧,还是自己解决了,昏呀,分又不能收回来,

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧