xtermjs重复发送
使用vue + xtermjs + websocket开发网页ssh,核心代码如下:
initTerminal() {
console.log("初始化终端");
this.term = new Terminal({
cursorBlink: true,
theme: {
background: '#1f2937',
foreground: '#f3f4f6',
cursor: '#93c5fd'
}
});
this.ws = new WebSocket('/webssh');
const attachAddon = new AttachAddon.AttachAddon(this.ws);
const fitAddon = new FitAddon.FitAddon();
this.term.loadAddon(attachAddon);
this.term.loadAddon(fitAddon);
this.term.open(document.getElementById('terminal'));
fitAddon.fit();
// 同步终端尺寸变化
this.term.onResize(({cols, rows}) => {
this.ws.send(JSON.stringify({
type: 'resize',
cols: cols,
rows: rows
}));
});
this.ws.onopen = () => {
this.ws.send(JSON.stringify(this.config));
this.connected = true;
this.connecting = false;
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
alert('连接失败,请检查配置信息');
this.resetConnection();
};
window.addEventListener('resize', () => {
fitAddon.fit();
this.ws.send(JSON.stringify({
type: 'resize',
cols: this.term.cols,
rows: this.term.rows
}));
});
this.term.onData(data => { // 输入与粘贴的情况
console.log("终端输入:", data); // 打印日志
this.ws.send(data)
})
},
调试中发现发送的指令会重复发2次,比如pwd
命令会发送ppwwdd
。
尝试删除onData
,能正常发送。推测应该是初始化AttachAddon(this.ws)
会自动监听键盘按键。
如果不需要这个特性,可以在初始化时添加选项参数:
const attachAddon = new AttachAddon.AttachAddon(this.ws, {
bidirectional: false,
});
再手动添加onData
监测,参考这里。