gpt4 book ai didi

jquery - 将服务器端变量发送到客户端node.js和socket.io

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

我要问一个非常n00b的问题。因为我一直在阅读文档,并在这里进行挖掘,但它只是没有进入我的大脑。

我正在关注本教程:http://socket.io/get-started/chat/

我想知道如何在服务器端设置变量的值,并将该值传递给客户端以在警报中呈现。

我知道这是错误的,因为 alert(alertMsg); 返回未定义,但这是我的起点:

服务器端:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var port = process.env.PORT || 3000;

var alertMsg = 'alert message goes here';

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

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

console.log('a user connected');

socket.on('connect', function(alertMsg){
io.emit('alert: ' + alertMsg);
});

socket.on('chat message', function(msg){
console.log('message: ' + msg);
io.emit('chat message', msg); // send the message to everyone
});

socket.on('disconnect', function(){
console.log('user disconnected');
});
});

http.listen(3000, function(){
console.log('listening on %d', port);
});

客户端:

<!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="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;
});
// I know this isn't right ATM...
socket.on('connect', function(alertMsg){
alert(alertMsg);
});

socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>

我肯定错过了一些非常明显的东西。我就是看不到。

建议?

谢谢。

最佳答案

客户端必须监听服务器发送的相同消息名称。现在,您正在使用io.emit('alert: ' + alertMsg);从服务器发送可变消息名称。 ,因此无法在客户端中监听该特定消息。

将服务器更改为:

io.emit('alert', alertMsg);

添加到客户端:

socket.on('alert', function(msg) {
alert(msg);
});

看看这是如何发送和监听相同的消息名称的?

<小时/>

然后,还要删除此代码,因为连接时不会发送alertMsg(稍后会出现):

  // I know this isn't right ATM... 
socket.on('connect', function(alertMsg){
alert(alertMsg);
});

关于jquery - 将服务器端变量发送到客户端node.js和socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28164317/

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