我正在尝试创建一个多用户/客户端UDP服务器,它将音频流发送给连接到服务器的任何人。
到目前为止它工作得很好但是如果我杀死其中一个客户端,它会在客户端关闭时抛出EndReceiveFrom中的错误,这意味着我再也不会调用BeginReceiveFrom。如果我尝试再次调用BeginReceiveFrom,它将抛出一个SocketException'现有连接被远程主机强行关闭'
这是我的服务器代码(不包括发送功能)。
public UdpServer(IPAddress ipAddress, int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
{
ExclusiveAddressUse = false
};
_socket.Bind(new IPEndPoint(ipAddress, port));
StartListening();
}
private void StartListening(EndPoint epSender = null)
{
if (epSender == null)
epSender = new IPEndPoint(IPAddress.Any, 0);
_socket.BeginReceiveFrom(ByteData, 0, ByteData.Length, SocketFlags.None, ref epSender, OnReceive, epSender);
}
private void OnReceive(IAsyncResult ar)
{
var sender = (EndPoint)ar.AsyncState;
try
{
var clients = new IPEndPoint(IPAddress.Any, 0);
var epSender = (EndPoint)clients;
_socket.EndReceiveFrom(ar, ref epSender);
if(!_clients.Any(c => c.Equals(epSender)))
_clients.Add(epSender);
StartListening(epSender);
}
catch (Exception ex)
{
_clients.Remove(sender);
Console.WriteLine(ex.Message);
}
}
我的客户非常基本。我发送了一条'hello'的消息,因此服务器知道客户端存在
var udp = new UdpClient();
var ipEp = new IPEndPoint(IPAddress.Parse(ip), 9009);
udp.Connect(ipEp);
var bytes = Encoding.ASCII.GetBytes("Hello");
udp.Send(bytes, bytes.Length);
udp.BeginReceive(OnBeginReceive, new object());