我是网络编程的新手,我遇到了一些问题,我一直在测试作为局域网聊天程序的基础。
服务器代码:
public static void Main()
{
UdpClient publisher = new UdpClient("230.0.0.1", 8899);
UdpClient subscriber = new UdpClient("230.0.0.2", 8800);
IPAddress addr = IPAddress.Parse("230.0.0.1");
subscriber.JoinMulticastGroup(addr);
Console.WriteLine("Running chat program at 230.0.0.1:8899");
while (true)
{
IPEndPoint ep = null;
byte[] chats = subscriber.Receive(ref ep);
string chatstring = Encoding.ASCII.GetString(chats);
Console.WriteLine(chatstring);
string msg = String.Format(chatstring);
byte[] sdata = Encoding.ASCII.GetBytes(msg);
publisher.Send(sdata, sdata.Length);
System.Threading.Thread.Sleep(500);
}
}
客户端程序:
static void Main(string[] args)
{
UdpClient subscriber = new UdpClient("230.0.0.1", 8899);
IPAddress addr = IPAddress.Parse("230.0.0.1");
subscriber.JoinMulticastGroup(addr);
IPEndPoint ep = null;
Thread SendChats = new Thread(Send);
SendChats.Start();
while (true)
{
byte[] receivedbytes = subscriber.Receive(ref ep);
string receivedchats = Encoding.ASCII.GetString(receivedbytes);
Console.WriteLine(receivedchats);
Thread.Sleep(500);
}
}
static void Send()
{
UdpClient publisher = new UdpClient("230.0.0.2", 8800);
while (true)
{
string msg = Console.ReadLine();
byte[] sdata = Encoding.ASCII.GetBytes(msg);
publisher.Send(sdata, sdata.Length);
Thread.Sleep(400);
}
}
通过我的计算,服务器程序应该从客户端接收数据,但是,在输入和传递消息之后,从来没有任何事情可以通过。我错过了什么吗?
答案 0 :(得分:1)
您的订阅者是否在服务器中加入了错误的多播?
UdpClient subscriber = new UdpClient("230.0.0.2", 8800);
IPAddress addr = IPAddress.Parse("230.0.0.1");
subscriber.JoinMulticastGroup(addr);
可能应该是:
IPAddress addr = IPAddress.Parse("230.0.0.2");
此外 - 您是否在客户端/服务器之间有任何路由器/交换机,因为它们将阻止多播流量,除非特别配置这样做。