我正在制作一个即时消息聊天应用程序,并且在让我的客户端从我的服务器接收数据时遇到问题。有谁可以向我解释为什么会这样?
app.js
var http = require("http");
var express = require("express");
var socket = require("socket.io");
var app = express();
app.use(express.static(__dirname + "/public"));
var server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);
io.sockets.on("connection", function(client) {
client.on("join", function(name) {
client.set("nickname", name);
console.log(name + " connected."); // logs name correctly
client.broadcast.emit("names", name);
});
});
的index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var server = io.connect("http://localhost:8080");
server.on("connect", function(data) {
nickname = "";
while (nickname == null || nickname.trim() == "") {
nickname = prompt("Enter name");
}
server.emit("join", nickname);
});
server.on("names", function(data) {
document.getElementById("txtNames").value = data;
});
</script>
</head>
<body>
<textarea id="txtNames"></textarea>
</body>
</html>
答案 0 :(得分:1)
你知道广播是什么吗?当您从套接字广播消息时,该消息将发送到除触发事件的套接字之外的所有连接的客户端。你的情况也一样。如果您要向已连接的客户端发出names
事件,请使用
socket.emit("names", name);