套接字.io祝辞简单的服务器到客户机消息

Socket.io > Simple server to client message

本文关键字:服务器 客户机 消息 简单 io 套接字      更新时间:2023-09-26

我的插座之间的问题。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),我没有得到一个警报。服务器列表工作,我可以访问页面没有任何问题。

我现在是一个套接字新手。Io/javascript(昨天安装的),如果你有关于套接字的好信息页面。请在此主题下张贴链接,谢谢。

您在连接时就发出新闻消息,因此在您单击按钮时它已经被触发。试着这样修改代码,你应该会看到你的警告:

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');
)};