UDP服务器端求助,有时能收到数据,有时不能?

liu_xyzq 2009-07-18 09:13:41
在一个端口上,即实现UDP广播,又实现接收消息。现在广播已经没有问题, 可是接收消息部分,有时启动服务能收到数据,有时启动服务不能收到数据,不知道是什么原因。以下是接收消息的线程代码。

//LAN UDP服务器程序
public void UDPListen()
{
try
{
Socket soUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

IPEndPoint localIpEndPoint = new IPEndPoint(IPAddress.Parse(serv_ip), LAN_port);
soUdp.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
soUdp.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);//设置为广播模式


soUdp.Bind(localIpEndPoint);

MessageBox.Show("UDP接收启动");

while (true)
{
Byte[] received = new Byte[256];
//IPEndPoint tmpIpEndPoint = new IPEndPoint(IPAddress.Parse(serv_ip), LAN_port);
//EndPoint remoteEP = (tmpIpEndPoint);
//int bytesReceived = soUdp.ReceiveFrom(received, ref remoteEP);
int bytesReceived = soUdp.Receive(received);

String dataReceived = System.Text.Encoding.ASCII.GetString(received);
MessageBox.Show("dataReceived:" + dataReceived);

Data_chuli(received);
/*
String returningString = "The Server got your message through UDP: " ;

Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes(returningString.ToCharArray());
MessageBox.Show("begin");

soUdp.SendTo(returningByte,soUdp.RemoteEndPoint);
MessageBox.Show("end");
*/
}

}
catch (SocketException se)
{
Console.WriteLine("A Socket Exception has occurred!" + se.ToString());
}
}
void Data_chuli(Byte[] received)
{
String dataReceived = System.Text.Encoding.ASCII.GetString(received);

MessageBox.Show("shujuchuli SampleClient is connected through UDP.");

MessageBox.Show(dataReceived);

}
...全文
192 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
裸奔的蜗牛 2010-11-23
  • 打赏
  • 举报
回复
问题解决没 我也是这样的问题?楼主解决了给说下

裸奔的蜗牛 2010-11-23
  • 打赏
  • 举报
回复
注册了 还不能看 ???
liu_xyzq 2009-07-20
  • 打赏
  • 举报
回复
soUDP是在线程里面的,如果用soUDP.close,是在没结束线程的时候结束通信。不是在结束线程时借宿的。功能不一样。
MessageBox.Show()是调试程序时用的,这不是主要问题。
风之影子 2009-07-18
  • 打赏
  • 举报
回复
楼上正解
  • 打赏
  • 举报
回复
试试
soUdp .Shutdown(SocketShutdown.Both);
soUdp.Close();
c168ylf 2009-07-18
  • 打赏
  • 举报
回复
学习了
shuxiangzuiyue 2009-07-18
  • 打赏
  • 举报
回复
我现在一见到有关UDP和TCP就头晕。最近整得好烦,一进这样的房间(语音效果:高质立体声/UDP)就无声;而这样的就语音正常(语音效果:高质立体声/TCP)。向大侠们求救 !!!!
netstray 2009-07-18
  • 打赏
  • 举报
回复
学习中…………
龍月 2009-07-18
  • 打赏
  • 举报
回复
方法1:
MessageBox.Show()导致客户端中断接受数据,但是服务端一直在发数据,中断期间数据丢失。
都不要用MessageBox.Show;将一切信息打在textbox里面。

方法2:
最好 发送端 每发一个数据包都 执行一下
Thread.sleep(5000);停止5秒让你及时按下 MessageBox.Show 弹出的“确定”按钮也行
cnzdgs 2009-07-18
  • 打赏
  • 举报
回复
UDP不是基于连接的协议,不需要关闭连接。UDP是不可靠协议,有时收不到包是常见现象,需要重发。
liu_xyzq 2009-07-18
  • 打赏
  • 举报
回复
目前已经知道,原因出在,关闭线程时,没有关闭socket连接,请问如何在关闭线程时关闭socket连接

110,539

社区成员

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

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

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