【问题标题】:Socket.io > Simple server to client messageSocket.io > 简单的服务器到客户端的消息
【发布时间】:2014-10-02 07:52:57
【问题描述】:

socket.io 和 HTML5 之间的问题

Javascript 服务器:

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('connection', function (socket) {
    socket.emit('news', 'Hello');
});
http.listen(3000, function () {
    console.log('listening on *:3000');
});

HTML5:

<html>

<head>
    <meta charset="UTF-8">
    <title>My Title</title>
</head>

<body>
    <input type="button" id="getButton" value="Get Rooms">
    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
        var socket = io();
        $("#getButton").click(function () {
            socket.on('news', function (data) {
                alert(data);
            });
        });
    </script>
</body>

</html>

当我单击按钮(ID:getButton)时,我没有收到警报。服务器正在工作,我可以毫无问题地访问该页面。

我目前是socket.io/javascript(昨天安装)的新手,如果您有关于socket.io的信息丰富的页面,请在此主题下发布链接,谢谢。

最好的问候

【问题讨论】:

    标签: javascript jquery html node.js socket.io


    【解决方案1】:

    您在连接后立即发出新闻消息,因此在您单击按钮时它已经触发。尝试将您的代码更改为此,您应该会看到您的警报:

    var socket = io();
    socket.on('news', function(data) {
        alert(data);
    });
    

    您可以使用以下方式触发按钮上的事件:

    服务器:

    io.on('connection', function(socket) {
        //socket.emit('news','Hello');  
    });
    
    // Return the news when it's requested
    io.on('giveMeNews', function(socket) {
        socket.emit('news', 'Here is your news');
    });
    

    客户:

    // Listen for the news message
    socket.on('news', function(data) {
        alert(data);
    });
    
    // Request news from the server
    $("#getButton").click(function() {
        socket.emit('giveMeNews');
    )};
    

    【讨论】:

    • 谢谢,但是如何通过单击按钮触发事件?
    • 感谢您的工作,我复制了代码,但它不起作用。我重新启动了服务器,但没有任何反应。
    • 尝试在服务器代码的连接处理程序中放置一条日志语句,以确保客户端正在连接。还要检查浏览器控制台是否有任何错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2018-11-02
    • 2020-12-25
    • 2012-04-07
    • 1970-01-01
    • 2014-11-01
    • 2017-04-22
    相关资源
    最近更新 更多