這就是我在Laravel所做的工作,您需要安裝Predis,socket.io,ratchet和其他依賴項。請檢查https://laracasts.com/discuss/channels/general-discussion/step-by-step-guide-to-installing-socketio-and-broadcasting-events-with-laravel-51
製作一個自定義的工匠命令使用棘輪
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Ratchet\Server\IoServer;
class webSockets extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'run:socket {port?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run websockets for specified port';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$port = $this->argument('port');
$server = IoServer::factory(
new ChatController(),$port
$server->run();
}
}
你的控制器應運行某些端口上的WebSockets像下面
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class ChatController implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn) {
}
public function onMessage(ConnectionInterface $from, $msg) {
//FIRE A BROADCAST EVENT HERE
event(new MessageBroadcast(
$message,
$datetime,
$user_id
)
);
}
public function onClose(ConnectionInterface $conn) {
}
public function onError(ConnectionInterface $conn, \Exception $e) {
}
}
廣播類應該如下
namespace App\Events;
use App\Events\Event;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class MessageBroadcast extends Event implements ShouldBroadcast
{
use SerializesModels;
public $message,$datetime,$userid;
public function __construct($message,$datetime,$userid)
{
$this->message = $message;
$this->datetime = $datetime;
$this->userid = $userid;
}
public function broadcastOn()
{
return ['test-channel'.$this->user_id];
}
}
JavaScript部分訂閱的頻道
<script src="{ { asset('js/socket.io.js') } }"></script>
<script>
//var socket = io('http://localhost:3000');
var socket = io('http://yourip:5000');
socket.on("test-channel1:App\\Events\\EventName", function(message){
// get user on console
console.log(message);
});
</script>
您需要在研究背景運行以下命令
1. php artisan run:socket <port_no>
2. Node yourjavascript.js
[編寫一個聊天應用程序的可能的複製](http://stackoverflow.com/questions/3682198/writing-a-chat-application) –
你顯示一個例子的鏈接,然後問任何想法?在SO上,人們在代碼問題上的幫助?並說出你的朋友停止upvote你的問題。你的問題是廣泛的,而不是代碼相關。 – JustOnUnderMillions
@JustOnUnderMillions,那個鏈接只是websocket的演示教程。除了代碼問題之外,我們也可以討論架構問題。我只想知道如何實現上述方法 –