如何在vue和socket.io中使用URL发送私人消息

时间:2020-10-12 10:38:40

标签: javascript node.js vue.js socket.io

我的目标是使用socket.io共享一个URL,并通过URL创建私人房间。我从未在项目中使用过它,现在我为heroku创建了一个简单的server.js文件,并为vue应用程序创建了带有浏览器扩展程序的vue应用程序,该应用程序将充当socket.io的客户端。 从这个基本示例中,我正在尝试实现私人对话。

const express = require('express');
//const cors = require('cors')
const socketIO = require('socket.io');

const PORT = process.env.PORT || 3000;
const INDEX = '/index.html';

const server = express()
// I don't have any index on heroku
  //.use((req, res) => res.sendFile(INDEX, { root: __dirname })) 
//  .use(cors())
  .listen(PORT, () => console.log(`Listening on ${PORT}`)) // just listen to the port
  

const io = socketIO(server, {
  path: '/p'
});

io.on('connection', (socket) => {
  console.log('Client connected', socket);
// here I need to use socket or io.on() on server? 
// how I can pass the client A id that is in the url eg. https://myheroku-app.herokuapp.com/p/fgfhc65c5 to ->socket.join(url) ?
  socket.on('disconnect', () => console.log('Client disconnected'));
});
CLIENT SIDE
//supposing that the url is https://my-herokuapp.herokuapp.com/p/whqh21o87st
// assuming v-model is teking only the code from user
console.log(this.url) // will log whqh21o87st that is inserted by the user or taken from 
//chrome://extensionid/p/whqh21o87st <- in vue-router dynamic route to take -> whqh21o87st  
const socket = io(url);
//socket.on('connect', => {  socket.emit() })

我不确定套接字配置的路径,我想用户会连接到p/socketId吗? 如何将客户端ID从客户端A传递到服务器,然后将其从URL传递到客户端B?我需要快递来收听路由,或者有更好的解决方案,例如vue-router

我正在从chrome扩展程序窗口弹出窗口运行的vue应用程序中,不确定是否可以在插入URL时使用chrome:// url协议直接打开扩展程序?如果可能的话,我可以附加socketId并直接用vuex或js处理它。

我将不胜感激每一个提示或帮助。

更新

在对该主题进行了一些研究之后,我在这里发现了一些问题,这些问题对我了解如何修改服务器和客户端代码有一些帮助。 在创建房间的客户上

const socket = io('server_url');
socket.on('connect', (socket) => {
 socket.emit('create_room', {socketId: socket.id,payload: payload});
});

在服务器上:

let rooms = [];

io.on('connected', (socket) => {
 socket.on('create_room', (data) => {
  rooms[data.socketId] = data.payload;
 });
 // join using url
 socket.on('access_room', (data) => {
  socket.join(data.roomId, () => {  
   // here I'm not sure how to pass the associated data payload, help needed
  //maybe Array.find() will do the trick?
//how i can send an automated reply with the payload taken from the array?
  });
 });
});

在客户端,当客户端单击chrome-extension://<extension_id>时,可以从URL加入会议室。我已经通过在web_accessible_resources文件的manifest.json内添加扩展名的专用页面解决了这一部分。此字段将确保如果安装了扩展名并已浏览其URL,则将打开该页面。就我而言 chrome-extension://abcdefghilmnopqrstuvxyzavc/index.html#<socket_id or room>

// take the url and parse to connect
const hash = window.location.hash;
const roomId = hash.split('#'); // not sure about, code not tested
const socket = io('server_url');
socket.on('connect', (socket) => { socket.emit('access_room', roomId) })

0 个答案:

没有答案