【发布时间】:2021-06-04 16:48:27
【问题描述】:
我对 node.js 还是比较陌生,所以我决定用一个简单的程序来练习。 我使用node.js、express和socket.io制作了这个程序来测试客户端和服务器之间的连接性。
这是我的 server.js
// Create an http server with Node's HTTP module.
const http = require('http');
// Create a new Express application
const express = require('express');
const app = express();
const clientPath = `${__dirname}/../client`;
console.log(`Serving static from ${clientPath}`);
app.use(express.static(clientPath));
const socketio = require('socket.io');
// Pass the http server the Express application
const server = http.createServer(app);
const io = socketio(server);
io.on('connection', function (socket) {
console.log("There's been a connection");
socket.on("console output", function (input) {
console.log(input)
});
socket.on("text alter", function(data){
var display = "'" + data + "' An interesting set of characters";
io.sockets.emit("display string", display);
})
})
//Listen on port 8080
server.listen(8080, function () {
console.log("Listening on port 8080");
})
这是我的 index.js
const socket = io();
let players = [];
function serverOutput(){
socket.emit("console output", "You suck at programming");
}
function serverAlter(){
const alterInput = document.querySelector('#userinput1').value;
socket.emit("text alter", alterInput);
}
socket.on("display string", function(){
const outputArea = document.querySelector('#outputspace1');
var fullLine = document.createElement("p");
outputArea.appendChild(fullLine);
})
最后是我的 index.html
<html lang="en">
<head>
<title>Home</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="main-menu" class="page-templates">
<h3>Part 1: Press the button to see the server send a message</h3>
<button onclick="serverOutput()">Server message</button>
<br>
<h3>Part 2: Type in a string, and the server will add to it</h3>
<input type="text" id="userinput1">
<div id="outputspace1">
</div>
<button onclick="serverAlter()">Create sentence</button>
<script src="/socket.io/socket.io.js"></script>
<script src="src/index.js"></script>
</body>
</html>
从代码的运行方式来看,服务器能够从客户端获取数据,但是当我尝试更改数据并将其发送回时,本应输出字符串的段落没有数据。我有一种感觉,我错误地实现了“io.sockets.emit()”,但请各位大神赐教,我将不胜感激。
【问题讨论】:
标签: javascript node.js express sockets socket.io