其他分享
首页 > 其他分享> > express使用socketIO,前后端跨域

express使用socketIO,前后端跨域

作者:互联网

1.前端实现socketIO跨域:

(1)vueconfig.js配置

const webpack = require("webpack");
module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        'assets': "@/assets", //静态资源文件夹
        // 'common': "@/common", //工具包文件夹
        'components': '@/components', //组件文件夹
        'network': '@/network', //网络请求文件夹
        'views': '@/views', //视图文件夹
        'util': '@/util' //工具类文件夹
      }
    },
    //支持jquery
    plugins: [
      new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "windows.jQuery": "jquery"
      })
    ]
  },
  //    // 配置跨域
  devServer: {
    //设置代理
    proxy: {

       '/socket.io': {
         target: 'http://localhost:3000',
         ws: true,
         changeOrigin: true
       }
    },
    disableHostCheck: true
  }
 
}

(2)新建socket.js

import io  from "socket.io-client";//socket
const socket = io('/');//此处本来根据跨域应该为const socket = io('/socket.io'),但是socketio的请求地址默认自带socket.io,所以此处只要传入'/'
Vue.use(socket);

2.express后端实现socketIo跨域

(1)首先封装mysocket.js,先新建mysocket.js

var socket = {}
var socket_io = require('socket.io');
function getSocket(server){

  var io = require('socket.io')(server,{ cors: true });
   // var io = socket_io.listen(server);//监听传入的server
   
     // 10.1connection监听单个连接.
   io.on('connection',function(socket){
    console.log("**************************************");
     console.log("我来了,宝贝");
     console.log("id为:"+socket.id+"的用户成功建立连接!");
     io.emit('this', { will: 'be received by everyone'})
     socket.on('send message',(data)=>{  
      console.log("接收到用户:"+socket.id+"的一条消息,消息实体对象信息为:",data)  
      // 通过new message事件给对应的socketID发送数据 
      console.log("此消息发送给socketID:",data.toSocketID) 
      socket.to(data.toSocketID).emit('new message',data);  
      });   
  /****************************************************************************** */
     //10.2监听进入聊天模块
     socket.on('enterChat',async()=>{
       console.log("该用户上线")
     })

  /****************************************************************************** */
     //10.3监听已读,已读则把已读标签设置为true
     socket.on("hasRead",async(data)=>{
        
    })

  /****************************************************************************** */   
    // 10.4监听断开
    socket.on('disconnect',async(reason)=>{
      console.log("id为"+socket.id+"的用户端口断开……断开原因:"+reason);
    })
  });
   console.log("启动socket...")
 }

socket.getSocket = getSocket;
//导出socket
module.exports = socket

(2)http协议跨域:在app.js引入

let express = require("express")
let app = express()
var port = ('3000');
app.set('port', port);

var http = require('http');
// 套接字模块
//创建HTTP server
var server = http.createServer(app);
// // 导入socket的封装方法
var socket = require("./weteach_routes/mySocket")
socket.getSocket(server);//使用http协议建立socket

//此处变成http listen
server.listen(port);
// 导出
module.exports = app;

(3)https协议跨域,在app.js引入

let express = require("express")
var https=require('https');
var fs=require('fs');
var privateKey=fs.readFileSync('./2_humianyuan.cn.key'); //此处是你的ssl证书文件
var certificate=fs.readFileSync('./1_humianyuan.cn_bundle.crt');// 此处是你的ssl证书文件
var credentials= {key:privateKey,cert:certificate};
let app = express()
var httpsPort = "3000"
var httpsServer = https.createServer(credentials,app);//创建https套接字
httpsServer.listen(httpsPort,'0.0.0.0');

// // 导入socket的封装方法
var socket = require("./weteach_routes/mySocket")
socket.getSocket(httpsServer);//使用https协议建立socket
// 导出
module.exports = app;

标签:跨域,socketIO,require,express,io,var,app,socket
来源: https://www.cnblogs.com/hmy-666/p/14727394.html