gpt4 book ai didi

javascript - Socket.io 客户端不接收来自服务器的消息

转载 作者:行者123 更新时间:2023-11-29 20:53:36 26 4
gpt4 key购买 nike

我正在将 Socket.IO 用于 websockets,我希望客户端在连接时在控制台中收到来自服务器的欢迎消息,但它不工作:

服务器:

var fs = require('fs');
var https = require('https');
var express = require('express');
var app = express();
var options = {
key:
fs.readFileSync('/myfolder/mykey.pem'),
cert:
fs.readFileSync('/myfolder/mychain.pem')
};

var serverPort = 3080;

var server = https.createServer(options,app);
var io = require('socket.io')(server);

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

server.listen(serverPort, function(){
console.log('Server is working');
//console.log(__dirname);
});


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

console.log("Connected!");
socket.broadcast.emit("Welcome","Good day sunshine!");
});

客户:

<script src="https://localhost:3080/socket.io/socket.io.js"></script>
<script>
var URL_SERVER = 'https://localhost:3080';
var socket = io.connect(URL_SERVER);

socket.on("Welcome", function(data){
console.log(data);
});

</script>

我在服务器端得到消息控制台,但在控制台客户端没有得到服务器应答。

我该如何解决?

最佳答案

To broadcast, simply add a broadcast flag to emit and send method calls. Broadcasting means sending a message to everyone else except for the socket that starts it.

引用:https://socket.io/docs/

关于javascript - Socket.io 客户端不接收来自服务器的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50492594/

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