我正在使用c#设置服务器,它具有包含Socket.ReceiveFrom的无限循环,因此该应用程序将一直处于空闲状态,直到收到消息为止,问题是我在网站上读取:“当应用程序完成时套接字上的通信,它需要关闭连接以释放资源”,这是否意味着每次我收到一条消息时都必须关闭套接字?
这样做意味着每次循环重复自我重复时,我都必须重新初始化套接字的构造函数,所以我搜索了一下:“套接字在应用程序终止时会自动关闭吗”,但没有找到任何答案这个。
以下两个代码将使其更加清晰:
static void Main(string[] args)
{
// With out closing
byte[] data = new byte[1024];
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 8888);
Socket sckt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sckt.Bind(endpoint);
IPEndPoint senderEndPoint = new IPEndPoint((long)IPAddress.Any.AddressFamily, 0);
EndPoint remote = (EndPoint)endpoint;
Console.WriteLine("Listening");
while (true)
{
// receive data from sender
int recv = sckt.ReceiveFrom(data, ref remote);
// Get sender ip address
senderEndPoint = (IPEndPoint)remote;
Console.WriteLine(senderEndPoint.Address.ToString());
string message = Encoding.ASCII.GetString(data, 0, recv);
// Console.WriteLine(message);
if (message.Equals("test"))
//do something
}
}
关闭时:
static void Main(string[] args)
{
Console.WriteLine("Listening");
while (true)
{
byte[] data = new byte[1024];
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 8888);
Socket sckt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sckt.Bind(endpoint);
IPEndPoint senderEndPoint = new IPEndPoint((long)IPAddress.Any.AddressFamily, 0);
EndPoint remote = (EndPoint)endpoint;
//receive data from sender
int recv = sckt.ReceiveFrom(data, ref remote);
//Get sender ip address
senderEndPoint = (IPEndPoint)remote;
Console.WriteLine(senderEndPoint.Address.ToString());
string message = Encoding.ASCII.GetString(data, 0, recv);
//Console.WriteLine(message);
if (message.Equals("lol"))
//do something
sckt.Close();
}
}