socket连接,以及通过Timer来实现每隔一分钟连接检测
public class TouchWebSocket
{
/// <summary>
/// 消息到达事件
/// </summary>
public static event EventHandler<SocketMessage> MessageReceivedEvent;
static TouchSocket.Http.WebSockets.WebSocketClient myWSClient = new TouchSocket.Http.WebSockets.WebSocketClient();
public static System.Timers.Timer timer = new System.Timers.Timer(60000);
static TouchWebSocket()
{
timer.Elapsed += Timer_Elapsed;
}
private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//连接
}
public static async Task ConnectAsync(string url)
{
await Task.Run(() =>
{
try
{
if (myWSClient.Online)
{
myWSClient.Close();
}
if (myWSClient.Connected == null)
{
myWSClient.Connected = (client, me) =>
{
};//成功连接到服务器
}
if (myWSClient.Disconnected == null)
{
myWSClient.Disconnected = (client, me) =>
{
};//从服务器断开连接,当连接不成功时不会触发。
}
if (myWSClient.Received == null)
{
myWSClient.Received = (client, byteBlock) =>
{
//从服务器收到信息
string socketStr = Encoding.UTF8.GetString(byteBlock.PayloadData.Buffer, 0, byteBlock.PayloadData.Len);
SocketMessage socketMessage = JsonConvert.DeserializeObject<SocketMessage>(socketStr);
MessageReceivedEvent?.BeginInvoke(null, socketMessage, null, null);
};
}
myWSClient.Setup(new TouchSocket.Core.TouchSocketConfig()
.SetRemoteIPHost(new TouchSocket.Sockets.IPHost(url))
)
.Connect();
}
catch (Exception ex)
{
}
});
}
public static async Task CloseAsync()
{
await Task.Run(() =>
{
try
{
if (myWSClient.Online)
{
myWSClient.Close();
}
}
catch (Exception ex)
{
}
});
}
public static bool IsConnected
{
get
{
if (myWSClient != null)
{
return myWSClient.Online;
}
return false;
}
}
}
连接
Task.Run(async () =>
{
if (!TouchWebSocket.IsConnected)
{
await TouchWebSocket.ConnectAsync(wsUrl);
if (TouchWebSocket.IsConnected)
{
if (!TouchWebSocket.timer.Enabled)
{
TouchWebSocket.timer.Start();
}
}
}
});