gpt4 book ai didi

node.js - socket.io - 当用户连接或断开连接时打印消息

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

我对 socket.io 或 node.js 非常陌生,所以我想知道如何在用户连接或断开连接时将消息打印到聊天中。搜索此网站时,有些答案不起作用,其他答案不是我的情况,因此无法起作用。
Index.js

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

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

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

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

Index.html

<!doctype html>
<html>
<head>
<title>Derpzy.ML</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>
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.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>
</body>
</html>

最佳答案

尚未测试过,但您会想做这样的事情。

服务器端:

//when socket is connected
io.on('connection', function(socket){

console.log('Yay, connection was recorded')

//emit message to all front-end clients
io.emit('chat message', 'some message sent to all users');

//handling disconnects
socket.on('disconnect', function() {
io.emit('chat message', 'some user disconnected');
});

});

客户端:

//on io.emit from backend (notice 'chat message' event has same name as server side)
socket.on('chat message', function(msg){

console.log('Yay, I got a message back from the server: ', msg)

//handle the message however you would like
$('#messages').append($('<li>').text(msg));

});

要测试服务器,您可以在“连接”回调中进行 console.log 以确保后端正在获取连接。

要测试客户端,您可以在“聊天消息”回调中控制台日志,以确保正在接收数据。另外,请务必检查您的开发者控制台,以确保错误与您尝试将数据附加到 DOM 的方式无关。

关于node.js - socket.io - 当用户连接或断开连接时打印消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41752538/

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