110,533
社区成员
发帖
与我相关
我的任务
分享
//Server端的UDPLIstener
public string[] Listener()
{
string returnData = string.Empty;
string[] msgArray;
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 5000);
UdpClient udpClient = new UdpClient(RemoteIpEndPoint);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
returnData += Encoding.ASCII.GetString(receiveBytes);
returnData += ";;" + RemoteIpEndPoint.Address.ToString() + ";;" + RemoteIpEndPoint.Port.ToString();
msgArray = Regex.Split(returnData, ";;");
//msg;;ip;;port
udpClient.Close();
}
catch (Exception ex)
{
//do something here
throw;
}
return msgArray;
}
//接收到客户端的消息后,向客户端发送消息,其中ip和port为上一个方法保存的ip和port
public static void Sender(IPAddress ip, int port, string msg)
{
try
{
IPEndPoint ipep = new IPEndPoint(ip, 5000);
UdpClient udpClient = new UdpClient();
Byte[] sendBytes = Encoding.ASCII.GetBytes(msg);
//udpClient.JoinMulticastGroup(ip);
udpClient.Send(sendBytes, sendBytes.Length, ipep);//发送
udpClient.Close();//断开连接
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
//问题是在客户端的UDPListener要侦听哪个端口,这样写客户端仍然收不到消息
public string Listener()
{
string returnData = string.Empty;
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 5000);
UdpClient udpClient = new UdpClient(RemoteIpEndPoint);
//UdpClient udpClient = new UdpClient(5000, AddressFamily.InterNetwork);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
returnData += Encoding.ASCII.GetString(receiveBytes);
udpClient.Close();
}
catch (Exception ex)
{
//do something here
MessageBox.Show(ex.ToString());
throw;
}
return returnData;//如果未接收到消息,返回值为空
}