这就是我在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的演示教程。除了代码问题之外,我们也可以讨论架构问题。我只想知道如何实现上述方法 –