The following column workerman tutorial will introduce to you how to make a simple chat room. I hope it will be helpful to friends in need!
1: The environment is under the window, thinkphp3.2
2: Download GatewayWork and put it in
Directory
3: Then double-click to open
This file starts the service
4: All logic is in
5 in the Events.php file: When the user connects to the server, trigger
, initialize, send client_id
6: When receiving the message,
starts this method, message is the data sent by the client
7: Attached code
/** * 当客户端发来消息时触发 * @param int $client_id 连接id * @param mixed $message 具体消息 */ public static function onMessage($client_id, $message) { //1:收到消息之后转成array() $data = json_decode($message,true); if(!$data){ return; } //2:判断类型,bind是client_id与用户id绑定 //say 发送消息的事件 switch ($data['type']) { //绑定 case 'bind': $from_id = $data['from_id']; //把获取的到用户id与client_id进行绑定 Gateway::bindUid($client_id,$from_id); return; //发送文字消息 case 'say': //获取到客户端传过来的信息 $text = $data['data']; $from_id = $data['from_id']; $to_id = $data['to_id']; //封装消息 $info = array( 'type'=>'text', 'data'=>$text, 'from_id'=>$from_id, 'to_id'=>$to_id, 'time'=>date('Y-m-d h:i:s',time()) ); Gateway::sendToUid($to_id,json_encode($info)); return; //发送图片 case 'img': $from_id = $data['from_id']; $to_id = $data['to_id']; $img = $data['img']; //封装消息 $info = array( 'type'=>'img', 'data'=>$img, 'from_id'=>$from_id, 'to_id'=>$to_id, 'time'=>date('Y-m-d h:i:s',time()) ); Gateway::sendToUid($to_id,json_encode($info)); return; } //推送给指定的uid // 向所有人发送 // Gateway::sendToAll(json_encode($info)); }
can easily realize point-to-point message exchange.
The above is the detailed content of workerman+thinkphp creates a simple chat room. For more information, please follow other related articles on the PHP Chinese website!