websocket实现前端vue-socket.io服务端koa2(socket.io)

liuliu-hai liuliu-hai     2022-12-18     300

关键词:

前端:(vue项目,main.js)

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from ‘vue‘
import App from ‘./App‘
import router from ‘./router‘

// import VueNativeSock from ‘vue-native-websocket‘
// Vue.use(VueNativeSock, ‘ws://localhost:3000‘,
// passToStoreHandler: function (eventName, event, next)
// event.data = event.should_have_been_named_data
// next(eventName, event)
//
// )


import VueSocketIO from ‘vue-socket.io‘

Vue.use(new VueSocketIO(
debug: true,
connection: ‘ws://localhost:8888/self‘,
forceNew: true,
// vuex:
// store,
// actionPrefix: ‘SOCKET_‘,
// mutationPrefix: ‘SOCKET_‘
// ,
options: path: "" //Optional options
))

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue(
el: ‘#app‘,
router,
components: App ,
template: ‘<App/>‘
)
 
前端--在组件中使用:(HelloWorld.vue 组件)
<template>
<div class="hello">
<h1> msg </h1>
<h2>Essential Links</h2>
</div>
</template>

<script>
export default
name: "HelloWorld",
data()
return
msg: "Welcome to Your Vue.js App"
;
,
mounted()
this.onsocket();

this.sockets.subscribe("client_event", data =>
console.log(data);
// this.msg = data.message;
);
,
sockets:
connect: function()
console.log("客户端检测到 socket connected------------");
,
server_event: function(data)
console.log(
‘ 服务端定义的事件名字:"server_event" socket server. eg: io.emit("server_event", data)‘
);
console.log(data);
,
methods:
onsocket()
this.$socket.emit("client_event", origin: "client" );
;
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2
font-weight: normal;
ul
list-style-type: none;
padding: 0;
li
display: inline-block;
margin: 0 10px;
a
color: #42b983;
</style>
 
 
 
----------------------------------------------------------------------------------------------------------------
 
 
 
服务端:(koa2项目,app.js)
 
const Koa = require(‘koa‘)
const app = new Koa()
const views = require(‘koa-views‘)
const json = require(‘koa-json‘)
const onerror = require(‘koa-onerror‘)
const bodyparser = require(‘koa-bodyparser‘)
const logger = require(‘koa-logger‘)

const index = require(‘./routes/index‘)
const users = require(‘./routes/users‘)



// error handler
onerror(app)

// middlewares
app.use(bodyparser(
enableTypes:[‘json‘, ‘form‘, ‘text‘]
))
app.use(json())
app.use(logger())
app.use(require(‘koa-static‘)(__dirname + ‘/public‘))

app.use(views(__dirname + ‘/views‘,
extension: ‘pug‘
))

// logger
app.use(async (ctx, next) =>
const start = new Date()
await next()
const ms = new Date() - start
console.log(`$ctx.method $ctx.url - $msms`)
)

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on(‘error‘, (err, ctx) =>
console.error(‘server error‘, err, ctx)
);


//using websocket
// const server = require(‘http‘).createServer(app.callback());
// const io = require(‘socket.io‘)(server);
// io.on(‘connection‘, client =>
// console.log("有连接动作");
// client.on(‘event‘, data => /* … */ );
// client.on(‘disconnect‘, () => /* … */ );
// );

const io = require(‘socket.io‘)();

// io.on(‘connection‘, client =>
 
// );

io.of(‘/self‘).on(‘connection‘, client =>
console.log("服务端检测到连接----") ;
var data_obj=
name:"name",
age:12
io.of(‘/self‘).emit(‘server_event‘,data_obj); // emit an event to all connected sockets

client.on("client_event",function(data)
console.log("client_event");
console.log(data)
)

client.on(‘disconnect‘, () => /* … */ );
);
io.listen(8888);


// server.listen(8888);

module.exports = app
 
 
 
 
----完----
 
上述代码复制粘贴可用。

springboot集成websocket,实现后台向前端推送信息(代码片段)

...xff0c;于是就使用到了MQTT,特此记录一下。一、什么是websocket?WebSocket协议是基于TCP的一种新的网络协议。它实现了客户端与服务器全双工通信,学过计算机网络 查看详情

springboot集成websocket,实现后台向前端推送信息(代码片段)

...xff0c;于是就使用到了MQTT,特此记录一下。一、什么是websocket?WebSocket协议是基于TCP的一种新的网络协议。它实现了客户端与服务器全双工通信,学过计算机网络 查看详情

bex5内使用websocket实现前端数据实时同步(代码片段)

1搭建运行websocket的环境(这里只用tomcat说明)为了能让websocket运行起来,需要tomcat7.0版本以上,但是目前X5使用的是tomcat6,可以通过以下两种方式达到条件1.1通过替换掉X5里面的tomcat来升级,替换步骤如下:step1 下载解压版... 查看详情

springboot2实现websocket前后端通信

参考技术A首先导包:接着创建WebSocketConfig配置类继续创建WebsocketServer服务ok,到此完成,接下来就是测试接口实现推送前端消息WebsocketController前端jsOK,完成了 查看详情

websocket实现前端vue-socket.io服务端koa2(socket.io)

前端:(vue项目,main.js)//TheVuebuildversiontoloadwiththe`import`command//(runtime-onlyorstandalone)hasbeensetinwebpack.base.confwithanalias.importVuefrom‘vue‘importAppfrom‘./App‘importrouterfrom‘./router‘/ 查看详情

播放框架 websocket 发生时不会向前端发送消息

】播放框架websocket发生时不会向前端发送消息【英文标题】:Playframeworkwebsocketisnotsendingmessagestofront-endwhenithappens【发布时间】:2017-06-2107:16:36【问题描述】:我们需要在for循环中向前端发送消息,我们考虑使用websocket来实现。我... 查看详情

后端go前端vue连接websocket失败failed

参考技术A是Vue.config.js配置代理的问题。后端工程师隶属于软件研发工程师,是从事软件开发相关工作人员,其主要职责是平台设计、接口设计和功能实现。主要职责集中在三大部分,分别是平台设计、接口设计和功能实现。平... 查看详情

springboot及springcloud实现websocket群发及单点发送

参考技术A引入3个文件1.WebSocketConfig2.WebSocketServer3、SendPassagesController4.前端页面(注意改一下)vue版本自行百度后端向前端推送数据 查看详情

2021-10-29利用nginx实现https的websocket转发(代码片段)

利用nginx实现https的websocket转发环境描述:web服务器为nginx,前端为一个vue项目后端为golang项目,为前端提供api服务域名的cname由cloudflare托管,并选择“始终使用HTTPS”前端需要使用websocket做实时显示和推送问题ÿ... 查看详情

利用websocket+vuex完成一个实时聊天软件(前端部分)(代码片段)

文章目录前言一、效果如图二、具体实现步骤1.引入Vuex2.webscoked实现总结前言这篇文章主要利用websocked建立长连接,利用Vuex全局通信的特性,以及watch,computed函数监听消息变化,并驱动页面变化实现实时聊天。一、效... 查看详情

猿创征文|前端进阶必备——websockt实现聊天室(附源码)(代码片段)

WebSockt实现聊天室1.websocket是什么?2.作用场景3.传统http实现推送技术的弊端4.WebSockt常用API5.WebSocket实现聊天室1.websocket是什么?WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送... 查看详情

猿创征文|前端进阶必备——websockt实现聊天室(附源码)(代码片段)

WebSockt实现聊天室1.websocket是什么?2.作用场景3.传统http实现推送技术的弊端4.WebSockt常用API5.WebSocket实现聊天室1.websocket是什么?WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送... 查看详情

node.js搭建简单服务器,用于前端测试websocket链接方法和性能测试

 WebSocket简介谈到Web实时推送,就不得不说WebSocket。在WebSocket出现之前,很多网站为了实现实时推送技术,通常采用的方案是轮询(Polling)和Comet技术,Comet又可细分为两种实现方式,一种是长轮询机制,一种称为流技术,这两... 查看详情

前端架构破局-nodejs落地websocket(代码片段)

...:框架中。但是也许你不清楚,Socket.IO并不是一个纯粹的WebSocket框架。它是将Websocket和轮询机制以及其它的实时通信方式封装成了通用的接口,以实现更高效的双向通信。严格来说,Websocket只 查看详情

swoole+redis+websocket实现点对点即时聊天(代码片段)

Swoole+Redis+webSocket实现点对点即时聊天场景webSocket服务端代码前端代码场景Swoole+Redis+webSocket实现点对点即时聊天。webSocket服务端代码我们需要通过LaravelCommand来实现,因为Swoole只能运行在PHPCLI模式下。1.生成Command类phpart... 查看详情

swoole+redis+websocket实现点对点即时聊天(代码片段)

Swoole+Redis+webSocket实现点对点即时聊天场景webSocket服务端代码前端代码场景Swoole+Redis+webSocket实现点对点即时聊天。webSocket服务端代码我们需要通过LaravelCommand来实现,因为Swoole只能运行在PHPCLI模式下。1.生成Command类phpart... 查看详情

哪个websocket服务器实现可以和rabbitmq结合?

】哪个websocket服务器实现可以和rabbitmq结合?【英文标题】:Whichwebsocketserverimplementationcanbecombinedwithrabbitmq?【发布时间】:2013-01-3121:43:40【问题描述】:您好,我们正计划将websocket服务器实现集成为我们的RabbitMQ系统的前端。目... 查看详情

springboot集成websocket,实现后台向前端推送信息(代码片段)

...xff0c;于是就使用到了MQTT,特此记录一下。一、什么是websocket?WebSocket协议是基于TCP的一种新的网络协议。它实现了客户端与服务器全双工通信,学过计算机网络都知道,既然是全双工,就说明了服务器可以主... 查看详情