大家好,昨天我第一次在台式电脑上安装了 Linux,只是想用 TUI 在 node.js 中编写一个非常简单的 websocket 应用程序。不幸的是,WebSocket 不支持...
大家好,昨天我第一次在台式电脑上安装了 Linux,只是想用 TUI 在 node.js 中编写一个超级简单的 websocket 应用程序。不幸的是,WebSocket 不起作用,因为它拒绝浏览器中的每个连接,并且当使用 wscat 时无法建立连接。Webserver 本身可以工作,但 websocket 不行:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const blessed = require('blessed');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
const screen = blessed.screen({
smartCSR: true,
title: 'Node.js Server'
});
const box = blessed.box({
top: 'top',
left: 'left',
width: '100%',
height: '90%',
content: 'Waiting for clients to connect...',
tags: true,
border: {
type: 'line'
},
style: {
border: {
fg: '#f0f0f0'
}
}
});
screen.append(box);
const list = blessed.list({
top: '90%',
left: 'left',
width: '100%',
height: '10%',
keys: true,
vi: true,
items: [],
style: {
selected: {
bg: 'blue'
}
}
});
screen.append(list);
screen.key(['escape', 'q', 'C-c'], () => process.exit(0));
screen.render();
let clients = [];
app.get('/', (req, res) => {
res.send('Server is running');
});
io.on('connection', (socket) => {
console.log(`Client connected: ${socket.id}`);
box.setContent(`Client connected: ${socket.id}`);
clients.push(socket);
list.addItem(`Client ${socket.id}`);
screen.render();
socket.on('disconnect', () => {
console.log(`Client disconnected: ${socket.id}`);
clients = clients.filter(client => client !== socket);
list.removeItem(list.getItemIndex(`Client ${socket.id}`));
box.setContent(`Client disconnected: ${socket.id}`);
screen.render();
});
socket.on('error', (err) => {
console.error(`Client error: ${err}`);
box.setContent(`Client error: ${err}`);
screen.render();
});
list.on('select', (item) => {
const selectedClient = clients[list.getItemIndex(item)];
const prompt = blessed.prompt({
top: 'center',
left: 'center',
width: '50%',
height: '25%',
label: ' Command ',
border: {
type: 'line'
},
style: {
border: {
fg: '#f0f0f0'
}
}
});
screen.append(prompt);
prompt.readInput('Enter command:', '', (err, command) => {
if (!err && command) {
selectedClient.emit('executeCommand', command);
}
screen.remove(prompt);
screen.render();
});
});
});
server.listen(4000, () => {
console.log('Server listening on port 4000');
box.setContent('Server listening on port 4000');
screen.render();
});
代码是否有问题或者 ubuntu 中的某些设置阻止了连接?
我已经尝试使用不同的端口和不同的 websocket 进行测试。当我使用 调用服务器时 curl
,会出现预期的结果。使用 wscat 我收到消息 error: socket hang up
.