套接字OnConnectionLost自定义事件
本文关键字:事件 自定义 OnConnectionLost 套接字 | 更新日期: 2023-09-27 18:22:08
我写了一个类,它本质上是一个心跳,客户端每x秒向服务器发送一条消息。
无耻的盗窃发送代码
private void SendUdpPacket() {
byte[] data = new byte[1024];
Socket udpClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
data = Encoding.ASCII.GetBytes("lubdub");
udpClientSocket.SendTo(data, 0, data.Length, SocketFlags.None, ipep);
}
无耻地被盗接收代码
void ReceiveData(IAsyncResult iar) {
byte[] buffer = new byte[1024];
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceiveFrom(iar, ref tempRemoteEP);
string stringData = Encoding.ASCII.GetString(buffer, 0, recv);
Console.WriteLine(stringData);
lastUpdate = DateTime.Now.ToUniversalTime();
if (!this.IsDisposed) {
udpServerSocket.BeginReceiveFrom(buffer, 0, 1024, SocketFlags.None, ref ep, new AsyncCallback(ReceiveData), udpServerSocket);
}
然后由内部计时器进行监控
private void clTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
try {
SendUdpPacket();
connected = true;
} catch {
connected = false;
}
}
private void srTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
// Calculate the Timespan since the Last Update from the Client.
timeSinceLastHeartbeat = DateTime.Now.ToUniversalTime() - lastUpdate;
if (timeSinceLastHeartbeat > TimeSpan.FromMilliseconds(Timer.Interval))
connected = false;
else
connected = true;
}
如果消息成功,则套接字已连接,这通过公共布尔值connected
显示
因此,在我的应用程序中,我会有一个运行以下内容的计时器:
private void ServerCheck() {
if (heartin.connected) {
GKstat = true;
GKStatus.Text = "GateKeeper Status: Connected";
} else {
GKstat = false;
GKStatus.Text = "GateKeeper Status: Disconnected";
}
}
然而,这并不理想,因为它需要客户端或服务器上的计时器来不断检查Heart
是否已连接。
我想知道将其转换为一组事件是否有益,比如OnConnectionLost
和OnConnected
我一直在四处寻找,阅读各种各样的页面,它们只会让我更加困惑。
这就是我目前拥有的
public delegate void OnConnectionLost(Heart sender, EventArgs e);
public delegate void OnConnected(object sender, EventArgs e);
public event OnConnectionLost ConnectionLost;
我的问题是,这会有益吗?如果是,我将如何创建事件,使其只在连接状态更改时启动?
这是布尔是邪恶的场景之一:我强烈建议您制作enum
,例如:
public enum ConnectionState
{
Disconnected = 0,
Disconnecting = 1,
Connecting = 2,
Connected = 3,
// etc.
}
然后可以将其用于ConnectionState
等特性。此外,通常使用标准的EventHandler<T>
委托,而不是您自己的自定义委托类型。例如:
public sealed class ConnectionStateEventArgs : EventArgs
{
public ConnectionState ConnectionState { get; private set; }
public ConnectionStateEventArgs(ConnectionState connectionState)
{
ConnectionState = connectionState;
}
}
public event EventHandler<ConnectionStateEventArgs> ConnectionStateChanged;
这将允许你扩展你的连接状态,超越你现在的简单"开关"。ConnectionState
属性与ConnectionStateChanged
事件相结合是我在各种API中注意到的一种常见做法。
要使其仅在连接状态真正发生更改时激发,只需在ConnectionState
属性中添加一个主体:
private ConnectionState _connectionState;
public ConnectionState ConnectionState
{
get { return _connectionState; }
set
{
if (value != _connectionState)
{
_connectionState = value;
var tmp = ConnectionStateChanged;
if (tmp != null)
tmp (this, new ConnectionStateEventArgs(value));
}
}
}
然后,您所需要做的就是为属性指定一个不同的值,事件就会触发。