gpt4 book ai didi

node.js - Socket.io 有人可以帮助我为什么连接/断开连接消息出现两次吗?

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:59 25 4
gpt4 key购买 nike

下面是我的服务器端代码,我想在其中显示用户是否已连接或断开连接。但是用户已连接和用户已断开连接消息出现两次。有人可以帮助我为什么它出现两次吗?

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res) {
res.sendfile('index.html');
});

io.on('connect', function(socket) {

socket.broadcast.emit('chat message', 'a user connected!');

socket.on('disconnect', function() {
socket.broadcast.emit('chat message', 'user disconnected');
});

socket.on('chat message', function(msg) {
socket.broadcast.emit('chat message', msg);
});

});


http.listen(3000, function() {
console.log('listening on *:3000');
});

客户端代码

<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>

<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
<script>
var typing = false;
var timeout = undefined;

function timeoutFunction(){
typing = false;
socket.emit(noLongerTypingMessage);
}

function onKeyDownNotEnter(){
if(typing == false) {
typing = true
socket.emit(typingMessage);
timeout = setTimeout(timeoutFunction, 3000);
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 3000);
}
}
</script>

</body>
</html>

最佳答案

您的客户文件中有两份此内容的副本:

script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>

删除其中一个。

关于node.js - Socket.io 有人可以帮助我为什么连接/断开连接消息出现两次吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38298983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com