javascript - 为什么我的 WebSocket 客户端总是在发送消息后重新加载?

标签 javascript php websocket chat ratchet

我正在尝试使用 WebSocket 进行聊天。为此,我使用 Ratchet。

为此,我使用 Ratchet 的指南: http://socketo.me/docs/hello-world

我的问题是,发送消息后,页面会重新加载,而没有任何代码实现。

index.html:

<html> <!-- index.html -->
<head>
</head>
<body>
    <h1>Menu</h1>
    <h2>Create a chat server on port 8080</h2>
    <button><a href="chat-server.php">Here</a></button>
    <hr>
    <h2>Join the chat server on port 8080</h2>
    <button><a href="chat-client.php">Here</a></button>
    <p>You'll have an error if it doesn't exist !</p>
</body>
</html>

连接.js:

var conn;
function init(){
   console.log("function : init");
   conn = new WebSocket('ws://localhost:8080');
   console.log(conn);
   conn.onopen = function(e) {
      var co = document.getElementById("connection");
      co.innerHTML="Connection established !";
};
conn.onmessage = function(e) {
    var content = document.getElementById("chat");
    content.innerHTML = content.innerHTML + "<li>"+ e.data+"</li>";
};
conn.onclose = function(){
    var co = document.getElementById("connection");
    co.innerHTML="Connection closed !";
}
conn.onerror = function(){
    alert("Connection failed : There in no server on this port !");
}
}
function closeCon(){
    conn.close();
}
function sendMessage(){
    var mes = document.getElementById("message").value;
    conn.send(mes, function(event){
        event.preventDefault();
        console.log(event);
    } );
}

聊天客户端.php:

<html><!-- chat-client.php -->
<head>
    <script src="../js/connection.js"></script>
</head>
<body onload="init()">
<h1>Chat in web browser</h1>
<p id="connection"> Connection closed !</p>
<div>
    <ul id="chat">

    </ul>
    <form>
        <input id="message" style="border: 1;">
        <button onclick="sendMessage()">Send</button>
    </form>
</div>
<hr>
<button onclick="closeCon()"><a href="index.html">Back to the menu</a></button>
</body>
</html>

聊天服务器.php:

<h1>Welcome on your server on port 8080</h1>

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;

// cd /Applications/MAMP/htdocs/MyRatchetFirstApp/
require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    8080
);
$server->run();

聊天.php:

<?php //Chat.php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
    // Store the new connection to send messages to later
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})<br/>";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
        foreach ($this->clients as $client) {
            if ($from !== $client) {
            // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "<br/>", $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
    }

    public function onClose(ConnectionInterface $conn) {
    // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected<br/>";
    }
    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}<br/>";
        $conn->close();
    }
}

composer.json:

    {
    "autoload": {
        "psr-0": {
            "MyApp": "src"
        }
    },
    "require": {
        "cboden/ratchet": "0.3.*"
    }
}

最后,这里是 tree of this project

最佳答案

这只是表单中发送消息的按钮。然后当我“提交”它时,它刷新了页面。如果您想了解帖子的历史记录,则应该删除此表单。

关于javascript - 为什么我的 WebSocket 客户端总是在发送消息后重新加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164712/

相关文章:

javascript - 从 jSON 初始化 jQuery dataTable 后如何删除下一个/上一个选项卡?

javascript - 使用 Ajax 在 PHP 中发表评论

php - 这个 jquery 有问题吗?

php - 如何将字符串值分配给 php 数组的索引?

sockets - 如何解密bet365套接字数据

javascript - Chrome 自动填充在我的 JS 之后执行

javascript - 使用 Node.js 通过 SSL 连接到 MongoDB

php - 如何同时(非阻塞)运行 2 个 PHP 脚本来监视 popen 命令?

javascript - 哪些浏览器支持 HTML5 WebSocket API?

javascript - WebSocketGateway 中的 WsException 不起作用