客户代码1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/socket.io/socket.io.js"></script>
<title>Document</title>
</head>
<body>
<button id="my_button">sending msg to same room client</button>
<script>
var roomNumber = prompt('what`s your roomNumber.');
const socket = io.connect();
socket.emit('joinABCD', {
roomNumber: roomNumber,
});
**
var button = document.getElementById("my_button");
button.onclick = function() {
socket.emit('message', {
message: 'can you see me roomnumber people?'
});
}; **
//no jquery accept in node.hs . ==>how to soleve?
socket.on('message2', (data) => {
alert(data.message);
});
</script>
</body>
</html>
服务器节点代码
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
// app.use(express.static(`${__dirname}/public`));
const server = http.createServer(app).listen(2000, () => {
console.log('http://127.0.0.1:2000');
});
app.get('/', (request, response) => {
response.sendFile(`${__dirname}/public/creatingRoom.html`);
});
const io = socketIo.listen(server);
io.sockets.on('connection', (socket) => {
let roomNumber = null;
socket.on('joinABCD', (data) => {
roomNumber = data.roomNumber;
socket.join(data.roomNumber);
});
socket.on('message', (data) => {
io.sockets.in(roomNumber).emit('message2', {
message: `${data.message}`,
});
});
});
客户端代码1和服务器代码彼此匹配,则它可以正常工作。
但是,如果我将代码1更改为代码2,将无法正常工作。下面的代码2
来自客户代码1
var button = document.getElementById("my_button");
button.onclick = function() {
socket.emit('message', {
message: 'can you see me roomnumber people?'
});
};
到客户代码2
$("#my_button").click(function() {
socket.emit('message', {
message: 'can you see me roomnumber people?'
});
});
如何在serverside中操作jquery源。请教我怎么做。
有人说我必须对模块cheerio
正确吗?
答案 0 :(得分:0)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
**<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.slim.js"></script>
<title>Document</title>**
</head>
<body>
<button>메시지 전송</button>
<script>
var roomNumber = prompt('방번호를 입력하세요.');
const socket = io.connect();
socket.emit('joinABCD',{
roomNumber:roomNumber,
})
$(document).ready(function(){
$('button').click(function(){
socket.emit('message',{
message: '우리방 사람들 보이세요?',
});
});
});
socket.on('message2' ,(data) => {
alert(data.message);
});
</script>
</body>
</html>
jquery无法运行的原因仅仅是不将 cdn 放在脚本代码中。
并且我意识到websocket脚本标记src代码src =“ / socket.io/socket.io.js”从来就不是真正的src,而是sudo src,这让我感到困惑。
/socket.io/socket.io.js代码本身是CDN
这几乎意味着