我尝试创建简单的控制台应用程序' Chat'使用UDP协议和多播。我只能从服务器向客户端发送消息。服务器代码:
using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace Server
{
class Program
{
static void Main(string[] args)
{
// Create object UdpClient
UdpClient udpClient = new UdpClient();
// IPAddress of group
IPAddress multicastaddress = IPAddress.Parse("224.192.168.255");
try
{
// Join group
udpClient.JoinMulticastGroup(multicastaddress);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
}
// Create object IPEndPoint
IPEndPoint remoteep = new IPEndPoint(multicastaddress, 2345);
// Print message
Console.WriteLine("Server is running ...\n\nEnter message: ");
// Data in Byte []
Byte[] buffer = Encoding.Unicode.GetBytes(Console.ReadLine ());
try
{
// Send data using IPEndPoint
udpClient.Send(buffer, buffer.Length, remoteep);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString ());
}
// Leave the group
udpClient.DropMulticastGroup(multicastaddress);
// Close connection
udpClient.Close();
}
}
}
客户端:
using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace Client
{
class Program
{
static void Main(string[] args)
{
// Create UDP client
UdpClient client = new UdpClient();
// Create new IPEndPoint
IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 2345);
// Set socket options
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
// Bind to IPEndPoint
client.Client.Bind(localEp);
// IP address
IPAddress multicastaddress = IPAddress.Parse("224.192.168.255");
try
{
// Join group
client.JoinMulticastGroup(multicastaddress);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
}
Console.WriteLine("Client is running ...\n\n");
// Receive data
Byte[] data = client.Receive(ref localEp);
string strData = Encoding.Unicode.GetString(data);
Console.WriteLine("Server: " + strData);
// Leave the group
client.DropMulticastGroup(multicastaddress);
// Close connection
client.Close();
}
}
}
如何发送来自服务器的消息并从客户端接收响应,此后发送下一条消息并从客户端接收响应等?是否可以使用UdpClient
类和多播来实现它?
非常感谢!