You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.1 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocket4Net;
namespace StartServerWPF.Modules.Main
{
public class WebsocketClient
{
public WebSocket webSocket4Net = null;
public void WebSocketInit()
{
Console.WriteLine("客户端");
webSocket4Net = new WebSocket("ws://localhost:5000/ws");
webSocket4Net.Opened += WebSocket4Net_Opened;
webSocket4Net.Error += new EventHandler<ErrorEventArgs>(WebSocket_Error);
webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
webSocket4Net.Open();
Console.WriteLine("客户端连接成功!");
Thread thread = new Thread(ClientSendMsgToServer);
thread.IsBackground = true;
thread.Start();
// webSocket4Net.Dispose();
}
public void ClientSendMsgToServer()
{
int i = 88;
while (true)
{
//Console.WriteLine($"客户端发送数据{i++}");
Thread.Sleep(TimeSpan.FromSeconds(2));
if (webSocket4Net.State == WebSocketState.Open)
{
webSocket4Net.Send("{\"type\":\"heartbeat\",\"utype\":\"device\",\"uid\":123}");
}
else if (webSocket4Net.State == WebSocketState.Closed)
{
Thread.Sleep(TimeSpan.FromSeconds(5));
webSocket4Net.Open();
}
}
}
private void WebSocket4Net_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Debug.WriteLine($"服务端回复数据:{e.Message}");
}
private void WebSocket4Net_Opened(object sender, EventArgs e)
{
// webSocket4Net.Send($"客户端准备发送数据!");
}
void WebSocket_Error(object sender, ErrorEventArgs e)
{
Debug.WriteLine("websocket_Error:" + e.Exception.ToString());
}
}
}