UDP服务器端求助,有时能收到数据,有时不能?
在一个端口上,即实现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);
}