dongnai1876 2016-05-11 05:50
浏览 161
已采纳

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

I'm trying to make a chat using WebSocket. In that purpose I use Ratchet.

For that, I'm using the guide from Ratchet : http://socketo.me/docs/hello-world

My problem is that after sending a message, the page reloads without any implementation of code for it.

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>

connection.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);
    } );
}

chat-client.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>

chat-server.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();

Chat.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.*"
    }
}

And finally, here,the tree of this project

展开全部

  • 写回答

1条回答 默认 最新

  • doujiao1984 2016-05-17 03:45
    关注

    That was just the button to send the message was in a form. Then when I "submit" it, it refreshed the page. If you want to have an history of the posts, you should remove this form.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 在更新角色衣服索引后,Sprite 并未正确显示更新的效果该如何去解决orz(标签-c#)
  • ¥15 VAE代码如何画混淆矩阵
  • ¥15 求遗传算法GAMS代码
  • ¥15 雄安新区高光谱数据集的下载网址打不开
  • ¥66 android运行时native和graphics内存详细信息获取
  • ¥100 求一个c#通过CH341读取数据的Demo,能够读取指定地址值的功能
  • ¥15 rk3566 Android11 USB摄像头 微信
  • ¥15 torch框架下的强化学习DQN训练奖励值浮动过低,希望指导如何调整
  • ¥35 西门子博图v16安装密钥提示CryptAcquireContext MS_DEF_PROV Error of containger opening
  • ¥15 mes系统扫码追溯功能
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部