大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说WebSocket 托盘服务 NotifyIcon 通知栏「建议收藏」,希望能够帮助大家进步!!!
ASP.NET Core 中的 WebSocket 支持
WebSocket
WebSocket 测试工具
1、WebSocket 属性
Socket.readyState 属性
CONNECTING 值为0,表示正在连接。
OPEN 值为1,表示连接成功,可以通信了。
CLOSING 值为2,表示连接正在关闭。
CLOSED 值为3,表示连接已经关闭,或者打开连接失败。
2、WebSocket 事件
open Socket.onopen 连接建立时触发
message Socket.onmessage 客户端接收服务端数据时触发
error Socket.onerror 通信发生错误时触发
close Socket.onclose 连接关闭时触发
addEventListener socket.addEventListener('open', function (event) {}); 事件监听器
*
*
*
*
3、WebSocket 方法
Socket.send() 使用连接发送数据
Socket.close() 关闭连接
*
*
*、WebSocketServerForm.cs
管理 NuGet 程序包:SuperWebSocketNETServer
代码语言:javascript复制using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WebSocket.Windows
{
public partial class WebSocketServerForm : Form
{
WebSocketServer ws;
//缓冲字节数组
byte[] buffer = new byte[2048];
string ipAddress_Connect;
string ipAddress_Close;
string ipAddress_Receive;
//存储session和对应ip端口号的泛型集合
Dictionary<string, WebSocketSession> socketSessionList = new Dictionary<string, WebSocketSession>();
public WebSocketServerForm()
{
InitializeComponent();
}
private void WebSocketServerForm_Load(object sender, EventArgs e)
{ }
private void Start_Click(object sender, EventArgs e)
{
ws = new WebSocketServer();
if (!ws.Setup(int.Parse(txtPort.Text)))
SetMessage("ChatWebSocket 设置WebSocket服务侦听地址失败");
else
SetMessage("ChatWebSocket 设置WebSocket服务侦听地址成功");
if (!ws.Start())
SetMessage("ChatWebSocket 启动WebSocket服务侦听失败");
else
SetMessage("ChatWebSocket 启动WebSocket服务侦听成功");
ws.NewSessionConnected = Ws_NewSessionConnected;
ws.NewMessageReceived = Ws_NewMessageReceived;
ws.SessionClosed = Ws_SessionClosed;
}
private void btnStop_Click(object sender, EventArgs e)
{
ws.Stop();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtMsg.Text = "";
}
private void btnSendMsg_Click(object sender, EventArgs e)
{
//从客户端列获取想要发送数据的客户端的ip和端口号,然后从sessionList中获取对应session然后调用send()发送数据
if (cmb_socketlist.Items.Count != 0)
{
if (cmb_socketlist.SelectedItem == null)
{
MessageBox.Show("请选择一个客户端发送数据!");
return;
}
else
{
//sessionList[cmb_socketlist.SelectedItem.ToString()].Send(txtSendMsg.Text);
socketSessionList[cmb_socketlist.SelectedItem.ToString()].Send(txtSendMsg.Text);
}
}
else
{
SetMessage("当前没有正在连接的客户端!");
}
txtSendMsg.Clear();
}
private void btnSign_Click(object sender, EventArgs e)
{ }
void Ws_NewSessionConnected(WebSocketSession session)
{
try
{
string message = string.Format("New Session Connected:{0}, Path:{1}, Host:{2}, IP:{3}",
session.SessionID.ToString(), session.Path, session.Host, session.RemoteEndPoint);
ipAddress_Connect = session.RemoteEndPoint.ToString();
ComboboxHandle(ipAddress_Connect, OperateType.Add);
socketSessionList.Add(ipAddress_Connect, session);
SetMessage($"Ws {ipAddress_Connect} 已连接! {message}");
}
catch (Exception e)
{
}
}
void Ws_NewMessageReceived(WebSocketSession session, string value)
{
if (value.ToString().Equals("IsHere**"))//客户端定时发送心跳,维持链接
return;
SetMessage($"{DateTime.Now} 收到 {session.SessionID} {value}");
}
void Ws_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
string message = string.Format("Session Close:{0}, Path:{1}, IP:{2}", value.ToString(), session.Path, session.RemoteEndPoint);
ipAddress_Close = session.RemoteEndPoint.ToString();
socketSessionList.Remove(ipAddress_Connect);
SetMessage($"{ipAddress_Close} 已关闭连接! {message}");
}
private void ComboboxHandle(string ipAddress, OperateType operateType)
{
if (operateType == OperateType.Add)
{
cmb_socketlist.Invoke(new Action(() => { cmb_socketlist.Items.Add(ipAddress); }));
}
if (operateType == OperateType.Remove)
{
cmb_socketlist.Invoke(new Action(() => { cmb_socketlist.Items.Remove(ipAddress); }));
}
}
private void SetMessage(string str)
{
txtMsg.Invoke(new Action(() => { txtMsg.AppendText(str "rn"); }));
}
enum OperateType
{
Add = 1, //添加
Remove = 2 //移除
}
}
}
只听到从架构师办公室传来架构君的声音:
青烟万条长,缭绕几百尺。有谁来对上联或下联?
*、WebSoket.html
代码语言:javascript复制此代码由Java架构师必看网-架构君整理
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var ws;
function WebSocketTest() {
if ("WebSocket" in window) {
console.log("WebSocket is supported by your Browser!");
// Let us open a web socket
ws = new WebSocket("ws://192.168.1.106:3310/");
console.log("Ln 13 readyState " ws.readyState);
switch (ws.readyState) {
case WebSocket.CONNECTING:
// do something
console.log("Ln 17 WebSocket.CONNECTING");
break;
case WebSocket.OPEN:
// do something
console.log("Ln 21 WebSocket.OPEN");
break;
case WebSocket.CLOSING:
// do something
console.log("Ln 25 WebSocket.CLOSING");
break;
case WebSocket.CLOSED:
// do something
console.log("Ln 29 WebSocket.CLOSED");
break;
default:
// this never happens
break;
}
ws.onopen = function () {
// Web Socket is connected, send data using send()
console.log("Ln 37 readyState open");
console.log("Ln 38 readyState " ws.readyState);
ws.send("Hello WebSocket");
console.log("Ln 40 onopen Message is sent");
};
ws.onmessage = function (evt) {
if (typeof evt.data === String) {
console.log("Ln 44 Received data string");
}
if (evt.data instanceof ArrayBuffer) {
var buffer = event.data;
console.log("Ln 49 Received arraybuffer");
}
console.log(evt.data);
var received_msg = evt.data;
console.log("Ln 53 onmessage Message is received: " received_msg);
};
ws.onclose = function (e) {
//当客户端收到服务端发送的关闭连接请求时,触发onclose事件
console.log("Ln 57 onclose");
}
//ws.error = function () {
// alert("Error Happended");
//};
ws.onerror = function (e) {
//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
console.log(e);
console.log("Ln 65 onerror");
}
ws.addEventListener('open', function (event) {
ws.send('Hello Server!');
console.log("Ln 69 addEventListener open");
});
ws.addEventListener("close", function (event) {
var code = event.code;
var reason = event.reason;
var wasClean = event.wasClean;
// handle close event
console.log("Ln 76 addEventListener close");
});
ws.addEventListener("message", function (event) {
var data = event.data;
// 处理数据
console.log("Ln 81 addEventListener message");
});
ws.addEventListener("error", function (event) {
// handle error event
console.log("Ln 85 addEventListener error")
});
}
else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
function send() {
ws.send(document.getElementById("txtMessage").value);
}
</script>
</head>
<body>
<a href="javascript:WebSocketTest()">Run WebSocket</a>
<br />
<input type="text" id="txtMessage" />
<input type="button" value="发送" onclick="send()" />
</body>
</html>
*、托盘服务
添加 System.Windows.Forms.NotifyIcon 控件
窗体 Activated 事件【激活事件】
窗体 SizeChanged 事件【尺寸改变事件】
NotifyIcon 控件 DoubleClick 事件【】
NotifyIcon 控件 Icon图标
*、TrayForm.cs
代码语言:javascript复制using Newtonsoft.Json;
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Windows.Forms;
namespace Tray.Windows
{
public partial class TrayForm : Form
{
WebSocketServer ws;
//缓冲字节数组
byte[] buffer = new byte[2048];
string ipAddress_Connect;
string ipAddress_Close;
//存储session和对应ip端口号的泛型集合
Dictionary<string, WebSocketSession> socketSessionList = new Dictionary<string, WebSocketSession>();
public TrayForm()
{
InitializeComponent();
}
private void TrayForm_Load(object sender, EventArgs e)
{
ws = new WebSocketServer();
string ip = ConfigurationManager.AppSettings["WebSocketIp"];
string port = ConfigurationManager.AppSettings["WebSocketPort"];
if (!ws.Setup(ip, int.Parse(port)))
SetMessage("ChatWebSocket 设置WebSocket服务侦听地址失败");
else
SetMessage("ChatWebSocket 设置WebSocket服务侦听地址成功");
if (!ws.Start())
SetMessage("ChatWebSocket 启动WebSocket服务侦听失败");
else
SetMessage("ChatWebSocket 启动WebSocket服务侦听成功");
ws.NewSessionConnected = Ws_NewSessionConnected;
ws.NewMessageReceived = Ws_NewMessageReceived;
ws.SessionClosed = Ws_SessionClosed;
#region 定时任务
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = Convert.ToInt32(interval);//执行间隔时间,单位为毫秒
timer.Start();
timer.Elapsed = new System.Timers.ElapsedEventHandler(Timer1_Elapsed);
#endregion
}
/// <summary>
/// 窗体 激活事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TrayForm_Activated(object sender, EventArgs e)
{
///不能弹出窗体,始终在托盘显示
//this.Visible = false;
}
/// <summary>
/// 窗体 尺寸改变事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TrayForm_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized) //判断是否最小化
{
this.ShowInTaskbar = false; //不显示在系统任务栏
notifyIcon1.Visible = true; //托盘图标可见
}
}
/// <summary>
/// notify 双击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.ShowInTaskbar = true; //显示在系统任务栏
this.WindowState = FormWindowState.Normal; //还原窗体
notifyIcon1.Visible = false; //托盘图标隐藏
}
}
void Ws_NewSessionConnected(WebSocketSession session)
{
try
{
string message = string.Format("New Session Connected:{0}, Path:{1}, Host:{2}, IP:{3}",
session.SessionID.ToString(), session.Path, session.Host, session.RemoteEndPoint);
ipAddress_Connect = session.RemoteEndPoint.ToString();
socketSessionList.Add(ipAddress_Connect, session);
SetMessage($"Ws {ipAddress_Connect} 已连接! {message}");
}
catch (Exception e)
{
}
}
void Ws_NewMessageReceived(WebSocketSession session, string value)
{
if (value.ToString().Equals("IsHere**"))//客户端定时发送心跳,维持链接
return;
session.Send(JsonConvert.SerializeObject(new { code = "200", message = "abcd" }));
SetMessage($"{DateTime.Now} 收到 {session.SessionID} {value}");
}
void Ws_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
string message = string.Format("Session Close:{0}, Path:{1}, IP:{2}", value.ToString(), session.Path, session.RemoteEndPoint);
ipAddress_Close = session.RemoteEndPoint.ToString();
socketSessionList.Remove(ipAddress_Connect);
SetMessage($"{ipAddress_Close} 已关闭连接! {message}");
}
private void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Invoke(new MethodInvoker(delegate ()
{
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false; //不显示在系统任务栏
notifyIcon1.Visible = true; //托盘图标可见
lblLoading.Visible = false;
btnOpen.Visible = true;
}));
}
private void SetMessage(string str)
{ }
}
}