所以,我一直在尝试实现多人可以同时输入的文本框。这就是HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>wecode.collaboration()</title>
...
<link rel="stylesheet" href="coding.css" />
<script src="/node_modules/socket.io/client-dist/socket.io.js"></script>
<script defer src="/webpages/codingspace/codinglogic.js"></script>
</head>
<body>
...
<div class="content">
<textarea id="codingSpace" rows="4" cols="50"></textarea>
</div>
</body>
</html>
这是附带的客户端代码。codinglogic.js
:
document.addEventListener("DOMContentLoaded", () => {
const socket = io();
const codingSpace = document.getElementById("codingSpace");
// Listen for code changes from the server and update the text area
socket.on("codeChange", (newCode) => {
codingSpace.value = newCode;
});
// Listen for user input and send code changes to the server
codingSpace.addEventListener("input", () => {
const newCode = codingSpace.value;
socket.emit("codeChange", newCode);
});
});
这是服务器端代码server.js
:
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const port = 3000;
app.use(express.static(__dirname + "/webpages/codingspace"));
app.use(
"/socket.io",
express.static(__dirname + "/node_modules/socket.io/client-dist")
);
app.get("/code", (req, res) => {
res.sendFile(__dirname + "/webpages/codingspace/coding.html");
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
})
// WebSocket handling
io.on("connection", (socket) => {
console.log("A user connected");
// Listen for changes from clients
socket.on("codeChange", (newCode) => {
// Broadcast the new code to all connected clients, including the sender
io.emit("codeChange", newCode);
});
// Handle disconnection
socket.on("disconnect", () => {
console.log("A user disconnected");
});
});
最后是我遇到的错误:
GET http://localhost:3000/socket.io/?EIO=4&transport=polling&t=OhRSvvL 404 (Not Found)
create @ polling.js:298
Request @ polling.js:237
request @ polling.js:190
doPoll @ polling.js:215
poll @ polling.js:96
doOpen @ polling.js:56
open @ transport.js:46
open @ socket.js:170
Socket @ socket.js:111
open @ manager.js:108
Manager @ manager.js:39
lookup @ index.js:29
(anonymous) @ codinglogic.js:2
1条答案
按热度按时间uujelgoq1#
解决了而不是
使用