- 在安裝目錄(以我的例子是D:\xampp\htdocs\ws)底下建立一個 src資料夾, 在src裡再建立一個MyApp資料夾(名字沒限制, 這裡以MyApp示範),
然後在MyApp裡建立一個管理訊息的應用程式的檔案Chat.php, 這個程式會聆聽4個事件:
- onOpen - 有新連線的時候會呼叫這個function
- onMessage - 有新訊息的事件
- onClose - 連線關閉的事件
- onError - 連線有錯誤的事件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters<?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})\n"; } public function onMessage(ConnectionInterface $from, $msg) { $numRecv = count($this->clients) - 1; echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n" , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's'); foreach ($this->clients as $client) { if ($from !== $client) { // The sender is not the receiver, send to each client connected $client->send($msg); } } } 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\n"; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "An error has occurred: {$e->getMessage()}\n"; $conn->close(); } }
- 再來, 我們要建立一個處理訊息往來的server, 在安裝目錄底下建立一個bin資料夾然後再建立一個chat-server.php的檔案
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
<?php use Ratchet\Server\IoServer; use Ratchet\Http\HttpServer; use Ratchet\WebSocket\WsServer; use MyApp\Chat; require dirname(__DIR__) . '/vendor/autoload.php'; $server = IoServer::factory( new HttpServer( new WsServer( new Chat() ) ), 8080 ); $server->run(); - 建好chat-server.php之後, 我們在該目錄下用cmd執行
php chat-server.php
來啟用"server". - 啟用後, 我們來看看是否有成功執行:
- 我們在根目錄(xampp是htdocs)建立一個test.html然後把底下的code貼上去
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
<!DOCTYPE html> <html> <head> <title>Ratchet Test</title> <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <script> var messages = []; // connect to the socket server var chat_conn = new WebSocket('ws://localhost:8080'); chat_conn.onopen = function(e) { console.log('Connected to server:', chat_conn); } chat_conn.onerror = function(e) { console.log('Error: Could not connect to server.'); } chat_conn.onclose = function(e) { console.log('Connection closed'); } // handle new message received from the socket server chat_conn.onmessage = function(e) { // message is data property of event object var message = JSON.parse(e.data); console.log('message', message); // add to message list var li = '<li>' + message.text + '</li>'; $('.message-list').append(li); } // attach onSubmit handler to the form $(function() { $('.message-form').on('submit', function(e) { // prevent form submission which causes page reload e.preventDefault(); // get the input var input = $(this).find('input'); // get message text from the input var message = { type: 'message', text: input.val() }; // clear the input input.val(''); // send message to server chat_conn.send(JSON.stringify(message)); }); }); </script> </head> <body> <h1>Chat App Using Ratchet</h1> <h2>Messages</h2> <ul class="message-list"></ul> <form class="message-form"> <input type="text" size="40" placeholder="Type your message here" /> <button>Post it!</button> </form> </body> </html> - 然後打開2個瀏覽器各自輸入
localhost/test.html
127.0.0.1/test.html
-
如果沒問題, 輸入訊息後就會看到下面的畫面
{
"autoload": {
"psr-0": {
"MyApp": "src"
}
},
"require": {
"cboden/ratchet": "^0.3.5"
}
}
如果不是, 請依照上面修改, 然後cmd 輸入 composer dumpautoload重新產生composer.json檔
您好,
回覆刪除目前是所有連入的人都在同一個room裡面,
想請教要怎麼修改,
才可以讓對話變成1對1呢?
謝謝您。