node.js - 您如何在电子中使用 socket.io?
问题描述
我正在尝试在电子应用程序中实现 socket.io。按照之前关于一个问题的建议,我遵循了这个聊天应用程序示例https://socket.io/get-started/chat/,然后尝试将其变成一个电子应用程序。但是现在好像功能不存在,我做错了什么?该应用程序启动,但我只看到我可以输入和提交的前端,但什么也没有回来。代码如下
main.js
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
index.js
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg)
});
});
索引.html
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function (e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function (msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
</body>
如果我使用 node index.js 它可以完美运行(我在这个问题中使用了端口 3000 的监听)但是 npm start 用作电子应用程序没有。请帮忙!!!!!
解决方案
推荐阅读
- laravel - 如何在 laravel 的模型定义中设置 Where 条件
- python - Pytorch 中基于磁带的 autograd 是什么?
- amazon-web-services - 放大代码生成模型在 Android 上无法正常工作
- css - 在 react-native 中覆盖按钮背景颜色
- python - 如何删除打印列表中的空格?
- amazon-web-services - 通过自定义标签获取 AWS Reservation Utilization
- mapping - GAMS 中的条件映射
- c++ - 读取未知编码c ++的文件
- docker - 我可以在 docker compose 中设置一个变量并多次使用它以获得更清晰的代码吗?
- office365 - 如何使用 SharePoint REST API 发现多地理位置租户中的所有网站