很久之前写着玩的一个前后端聊天小应用
后面闲了的话,准备再重新做点什么…
在线效果演示: https://intbird.net/#/socket.io/
目录
技术
1. 功能
1. 浏览器和浏览器之间 互发消息
2. 浏览器和手机端之间 互发消息
3. 采用https可信任证书连接
2. 后端
采用: node+express+socket.io
代码: https://github.com/intbird/socket.io-node-vue/tree/master/node
3. web端
采用: vue2 + vue-socket.io
代码: https://github.com/intbird/socket.io-node-vue
4. 手机端
android + socket.io-java + ssl
代码: https://github.com/intbird/socket.io-android-https
5. 资源
- socketio文档: https://socket.io/get-started/chat/
- express文档: https://expressjs.com/zh-cn/4x/api.html
- express数据库集成: https://expressjs.com/zh-cn/guide/database-integration.html
效果
1. 效果演示
在线演示:
https://intbird.net/#/socket.io/
开源代码:
https://github.com/intbird/intbird.net/
网页和网页端互发消息
手机端和网页端互发消息
步骤
1.创建node后端服务
这里仅为示例, 内部代码较多, 包括代理,证书,https,wss, path和端口等
- webstrom 新建 node.js Express App
2.install socket.io
npm install socket.io
3.修改bin/www
添加 socket-server 服务
...
var http = require('http');
var socketServer = require('../src/socket-server')
...
var server = http.createServer(app);
// 启动socket-server
socketServer(server)
server.listen(port);
4.../src/socket-server
const server_path = '/socket.io/'
module.exports = function SocketServer(server) {
const socketServer = require('socket.io')(server, {path: server_path})
socketServer.on('connection', (socket) => {
console.log('connected');
// 通知客户端接收的事件名
socketio.emit("onConnection", result)
});
}
5.运行 bin/www
当集成了socket.io-client的客户端连接同一个 path 后
会log出当前连接状态
2.创建vue前端
1.新建vue项目
2.安装socket.io客户端
npm install socket.io-client
npm install vue-socket.io
3.修改main.js
import VueSocketIO from 'vue-socket.io'
Vue.use(new VueSocketIO({
debug: false,
connection: 127.0.0.1:8083
options: { path: /socket.io/ }
}))
4.first-socket-vue.vue
接收刚才服务器发出的 onConnection 事件名
3.创建android客户端代码
源码: https://github.com/intbird/socket.io-android-https
5.完整demo和在线演示
vue在线效果演示: https://intbird.net/#/socket.io/
github开源地址: https://github.com/intbird/intbird.net/
6.https免费证书申请
- 申请免费的https获取cert文件
- express配置https的cert文件
const express = require('express')
const https = require('https')
const fs = require('fs')
var path = require('path')
var httpsServer = https.createServer({
cert: fs.readFileSync(path.join(__dirname, '../cert/intbird.net.pem')),
key: fs.readFileSync(path.join(__dirname, '../cert/intbird.net.key'))
}, express.app)
const socketio = require('socket.io')(httpsServer, {path: "/socket.io/"})
server.listen(8083 function () {
console.log(`\nsuccess : http://localhost:${port} \n`)
})
- express允许跨域
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Content-Type')
res.header('Access-Control-Allow-Methods', '*')
res.header('Content-Type', 'application/json;charset=utf-8')
next()
})
个人网站(待开发): https://intbird.net
文章来自:http://blog.csdn.net/intbird 转载请说明出处