在我的套接字应用程序中,我正在尝试将编程代码作为消息发送到另一个客户端。如果仅运行 HTML,它会完美地显示 Ace 编辑器。但是当我运行节点应用程序时.js ace编辑器不起作用。我已经下载了ace版本并在应用程序中安装了npm ace代码编辑器,但这里没有任何变化
是我的代码 应用.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
);
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
})
socket.on('chat message', function (msg) {
console.log("message: " + msg);
io.emit('chat message', msg);
});
});
http.listen(port, function () {
console.log('listening on *:' + port);
});
索引.html
<html>
<head>
<title>Socket.IO </title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#m {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
<script src="/ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var editor = window.ace.edit("m");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/javascript");
$(function () {
var socket = io();
var myvar = setInterval(task, 100)
function task() {
var code=editor.getValue();
socket.emit('chat message',code);
}
socket.on('chat message', function (msg) {
editor.setValue("the new text here");
});
});
</script>
</head>
<body>
<div id="m">function foo(items) {
var x = "All this is syntax highlighted";
return x;
} </div>
</body>
</html>
需要一个解决方案
您在该元素可用之前调用window.ace.edit("m");
。将脚本标记移动到文件末尾,或将 ace 初始化移动到 $ 调用中。