浅析websocket的基本应用spring boot + vue +C# + WPF
1.基本概念
首先websocket是基于H5的一种通信。在网页中如果定时获取服务器端的实时数据,我们常采用long poll 和ajax轮询的方式。但是在轮询过程中,由于根本没有新数据的改变,而造成一种资源的浪费,同时也不能够保证数据的实时性。long poll是一种保持长连接的方式获取数据,但是需要进行头文件的各种校验,也是一种资源的浪费。
websocket完美的解决了这种两种方式的不足,首先能够保证数据的实时性,同时保证资源的完整利用,是网页和服务端的全双工通信,即可以接收来自网页端的消息,同时可以发送通知网页端。websocket还支持多种方式,本篇讨论java,C#(WPF)和vue,即服务端为java,客户端分别为vue和WPF来进行验证。
2.基本原理
websocket是基于TCP的一种通信,所以在建立通信之前首先需要建立TCP的一系列连接(三次握手等)。
服务端采用Springboot来实现,首先在pom.xml中添加WebSocect的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
接下来建立WebSocket并实现ServerEndPoint 我这里采用注解的方式
package com.koalin.rpc.websocket;
import com.utils.DateTimeUtils;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @version 1.0
* @ClassName WebSocket
* @Author koalin
* @Description //TODO WebSocket的描述
* @Date 2019/12/24 23:27
*/
@ServerEndpoint("/koalin/websocket/{userName}")
@Component
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
private static Map<String, Session> sessionPool = new HashMap<String, Session>();
volatile static boolean isRunning = false;
private String userName;
@OnOpen
public void onOpen(Session session, @PathParam(value = "userName") String userName) {
this.session = session;
this.userName = userName;
webSockets.add(this);
sessionPool.put(session.getId(), session);
System.out.println(userName + "【websocket消息】有新的连接,总数为:" + webSockets.size());
if (webSockets.size()==1) {
isRunning = true;
new Runnable() {
@Override
public void run() {
while (true) {
try {
for (WebSocket client :
webSockets) {
String msg = "Hello I am WebSocekt " + client.userName + "我的时间:" + DateTimeUtils.DateTimeYYYYMMDDHHMMSS(new Date());
client.session.getAsyncRemote().sendText(msg);
System.out.println(msg);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
isRunning=false;
}
}
}
}.run();
}
}
@OnClose
public void onClose() {
if (webSockets.contains(this) ){
webSockets.remove(this);
System.out.println(this.userName+"【websocket消息】连接断开,总数为:" + webSockets.size());
}
}
@OnMessage
public void onMessage(String message,Session session) {
//System.out.println("【websocket消息】收到客户端消息:" + message);
System.out.println("【websocket消息】收到客户端消息:" + message);
}
// 此为广播消息
public void sendAllMessage(String message) {
for (WebSocket webSocket : webSockets) {
System.out.println("【websocket消息】广播消息:" + message);
try {
webSocket.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 此为单点消息
public void sendOneMessage(String userName, String message) {
System.out.println("【websocket消息】单点消息:" + message);
Session session = sessionPool.get(userName);
if (session != null) {
try {
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
添加WebSocketConfig 创建默认的EndPointServer
package com.koalin.rpc.websocket; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; /**
* @version 1.0
* @ClassName WebSocketConfig
* @Author koalin
* @Description //TODO WebSocketConfig的描述
* @Date 2019/12/24 23:36
*/
@Configuration
public class WebSocketConfig { /**
* @return
* @Author koalin
* @Description //TODO这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
* @Date 22:47 2019/12/24
* @Param
**/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
以上完成服务端代码
接下来先验证C#客户端
首选在nuget中下载websocket-sharp

创建WebSocketClient
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocketSharp; namespace WebSocketLib
{
public class WebSocketClient
{
private WebSocket ws;
private string url = "";
CancellationToken token = new CancellationToken();
public WebSocketClient(string url)
{ this.url = url;
} public void Start()
{ try
{
ws = new WebSocket(url, token, 102392,
() =>
{//OnOpen
return Task.Run(() =>
{
Console.WriteLine("websocket连接正常....");
});
},
(e) =>
{//OnClose
return Task.Run(() =>
{
Console.WriteLine("websocket关闭正常...");
});
},
(e) =>
{//OnMessage
return Task.Run(() =>
{
Console.WriteLine("接收到服务端的消息" + e.Text.ReadToEnd());
});
},
(e) =>
{//OnError
return Task.Run(() =>
{
Console.WriteLine("连接异常..." + e.Message);
});
}
); ws.Connect();
}
catch (Exception e)
{ Console.WriteLine(e.ToString());
}
}
{
{
await Task.Delay(1000);
while (true)
{
try
{
if (ws != null )
{
}
}
catch (Exception ex)
{
}
await Task.Delay(2000);
}
});
}
public void Close()
{
if (ws!=null)
{
ws.Close();
ws.Dispose();
}
}
}
}
简单的建立wpf窗体应用程序然后添加引用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace WebSocketDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent(); }
WebSocketLib.WebSocketClient client = null;
private void Test()
{ client = new WebSocketLib.WebSocketClient("ws://www.koalin.com:8081/koalin/websocket/test"); client.Start(); client.StartSendMessage();
} private void Button_Click(object sender, RoutedEventArgs e)
{
Test();
} protected override void OnClosed(EventArgs e)
{
if (client!=null)
{
client.Close(); }
base.OnClosed(e);
}
}
}
启动服务和客户端进行简单的验证


建立vue工程,然后添加如下websockt关键代码
initWebSocket () {
// 连接错误
this.websocket.onerror = this.setErrorMessage
// 连接成功
this.websocket.onopen = this.setOnopenMessage
// 收到消息的回调
this.websocket.onmessage = this.setOnmessageMessage
// 连接关闭的回调
this.websocket.onclose = this.setOncloseMessage
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = this.onbeforeunload
},
setErrorMessage () {
console.log('WebSocket连接发生错误 状态码:' + this.websocket.readyState)
},
setOnopenMessage () {
console.log('WebSocket连接成功 状态码:' + this.websocket.readyState)
},
setOnmessageMessage (event) {
// 根据服务器推送的消息做自己的业务处理
console.log('服务端返回:' + event.data)
},
setOncloseMessage () {
console.log('WebSocket连接关闭 状态码:' + this.websocket.readyState)
},
onbeforeunload () {
this.closeWebSocket()
},
closeWebSocket () {
this.websocket.close()
}
},
mounted() {
this.restaurants = this.loadAll();
// WebSocket
if ('WebSocket' in window) {
// var url='ws://www.koalin.com:8081/koalin/websocket/' + new Date();
this.websocket = new WebSocket('ws://www.koalin.com:8081/koalin/websocket/' + new Date());
console.log( this.websocket);
this.initWebSocket();
} else {
alert('当前浏览器 Not support websocket')
}
},
beforeDestroy () {
this.onbeforeunload()
}
启动vue服务。然后在网页中输入对应的链接。

完成简单的客户端与服务端的通信
浅析websocket的基本应用spring boot + vue +C# + WPF的更多相关文章
- spring boot+vue实现H5聊天室客服功能
spring boot+vue实现H5聊天室客服功能 h5效果图 vue效果图 功能实现 spring boot + webSocket 实现 官方地址 https://docs.spring.io/ ...
- spring boot + vue + element-ui全栈开发入门——开篇
最近经常看到很多java程序员朋友还在使用Spring 3.x,Spring MVC(struts),JSP.jQuery等这样传统技术.其实,我并不认为这些传统技术不好,而我想表达的是,技术的新旧程 ...
- spring boot + vue + element-ui全栈开发入门——基于Electron桌面应用开发
前言 Electron是由Github开发,用HTML,CSS和JavaScript来构建跨平台桌面应用程序的一个开源库. Electron通过将Chromium和Node.js合并到同一个运行时环 ...
- spring boot + vue + element-ui全栈开发入门
今天想弄弄element-ui 然后就在网上找了个例子 感觉还是可以用的 第一步是完成了 果断 拿过来 放到我这里这 下面直接是连接 点进去 就可以用啊 本想着不用vue 直接导入连接 ...
- 一个实际的案例介绍Spring Boot + Vue 前后端分离
介绍 最近在工作中做个新项目,后端选用Spring Boot,前端选用Vue技术.众所周知现在开发都是前后端分离,本文就将介绍一种前后端分离方式. 常规的开发方式 采用Spring Boot 开发项目 ...
- spring boot + vue + element-ui
spring boot + vue + element-ui 一.页面 1.布局 假设,我们要开发一个会员列表的页面. 首先,添加vue页面文件“src\pages\Member.vue” 参照文档h ...
- 喜大普奔,两个开源的 Spring Boot + Vue 前后端分离项目可以在线体验了
折腾了一周的域名备案昨天终于搞定了. 松哥第一时间想到赶紧把微人事和 V 部落部署上去,我知道很多小伙伴已经等不及了. 1. 也曾经上过线 其实这两个项目当时刚做好的时候,我就把它们部署到服务器上了, ...
- 部署spring boot + Vue遇到的坑(权限、刷新404、跨域、内存)
部署spring boot + Vue遇到的坑(权限.刷新404.跨域.内存) 项目背景是采用前后端分离,前端使用vue,后端使用springboot. 工具 工欲善其事必先利其器,我们先找一个操作L ...
- 给大家整理了几个开源免费的 Spring Boot + Vue 学习资料
最近抽空在整理前面的文章案例啥的,顺便把手上的几个 Spring Boot + Vue 的学习资料推荐给各位小伙伴.这些案例有知识点的讲解,也有项目实战,正在做这一块的小伙伴们可以收藏下. 案例学习 ...
随机推荐
- ”只用 1 分钟“ - 超简极速 Apk 签名 & 多渠道打包神器
众所周知,渠道包作为当下国内 Android 应用市场常见的分发方式,当 APP 和后台交互或进行数据上报时,会带上各自的 channel 渠道信息,以此方便企业 & 开发者统计 APP 在各 ...
- 【Github】 Github修改仓库的基本信息
前言 我们通常在刚开始了解学习使用github时,一般都是测试的使用,有时我们向里面添加了一些代买,如果想要修改信息并且是删除仓库重新创建提交,可以采用下面方法修改仓库信息,名称.描述等. 修改仓库描 ...
- MAUI与Blazor共享一套UI,媲美Flutter,实现Windows、macOS、Android、iOS、Web通用UI
1. 前言 距离上次发<MAUI初体验:爽>一文已经过去2个月了,本计划是下半年或者明年再研究MAUI的,现在计划提前啦,因为我觉得MAUI Blazor挺有意思的:在Android.iO ...
- SQL注入漏洞篇
一篇SQL注入漏洞汇总,更新中-- 如有缺陷 望大佬指正 SQL注入产生的原因? 当程序执行逻辑时没有对用户输入的参数做过滤处理,使参数直接与后台数据库产生逻辑交互,即SQL注入黑客就可以利用各种SQ ...
- 教你用VS code 生成vue-cli代码片段
可以自定义设置名字:name.json { "Print to console": { "prefix": "vue", "bod ...
- DDos、CC攻击与防御
DDoS介绍 DDoS是英文Distributed Denial of Service的缩写,意即"分布式拒绝服务",那么什么又是拒绝服务(Denial of Service)呢? ...
- CMU15445 (Fall 2019) 之 Project#2 - Hash Table 详解
前言 该实验要求实现一个基于线性探测法的哈希表,但是与直接放在内存中的哈希表不同的是,该实验假设哈希表非常大,无法整个放入内存中,因此需要将哈希表进行分割,将多个键值对放在一个 Page 中,然后搭配 ...
- Tapdata Cloud 2.1.4 来啦:数据连接又上新,PolarDB MySQL、轻流开始接入,可自动标记不支持的字段类型
需求持续更新,优化一刻不停--Tapdata Cloud 2.1.4 来啦! 最新发布的版本中,在新增数据连接之余,默认标记不支持同步的字段类型,避免因此影响任务的正常运行. 更新速览 ① 数 ...
- java-Stream的总结
JAVA中的Stream 01.什么是Stream Stream是JDK8中引入,Stream是一个来自数据源的元素序列并支持聚合操作.可以让你以一种声明的方式处理数据,Stream 使用一种类似用 ...
- Collection集合概述和集合框架介绍avi
集合概述 在前面基础班我们已经学习过并使用过集合ArrayList<E> ,那么集合到底是什么呢?· ~集合︰集合是java中提供的一种容器,可以用来存储多个数据集合和数组既然都是容器,它 ...