Swoole, Websocket 채팅방 만들기.

2167 단어 Swoole
1. 프런트엔드 CSS 코드


var wsServer = 'ws://   IP:9502';
var websocket = new WebSocket(wsServer);

//       
websocket.onopen = function (evt) {
    console.log("Connected to WebSocket server.");
};

//     
websocket.onclose = function (evt) {
    console.log("Disconnected");
};

//           
websocket.onmessage = function (evt) {

    console.log('Retrieved data from server: ' + evt.data);
	
	var json = JSON.parse(evt.data);
	
	var dat = new Date();
	
	var data = "<span style='color:blue;font-weight:bolder;font-size:14px;'>"+json['user']+" ("+dat.getHours()+":"+dat.getMinutes()+"):</span><span>"+json['message']+"</span><br />";
	$("#msgboard").append(data);
};

//     
websocket.onerror = function (evt, e) {
    console.log('Error occured: ' + evt.data);
};

$("#post").click(function() {
	var htm = $("#msg").val();
	websocket.send(htm);
});


2. 서버측 Server.php, php Server를 실행합니다.php
on('open', function ($ws, $request) {
    // var_dump($request->fd, $request->get, $request->server);

        global $ws;

        foreach ($ws->connections as $val) {
                $ws->push($val, '{"user":"'.$request->fd.'", "message":"    "}');
        }

});

//   websocket    

$ws->on('message', function ($ws, $frame) {
        echo "Message: {$frame->data}
"; $link = link_redis(); push_array($frame->fd, $link); $onlineUser = getOnlineUser($link); global $ws; foreach ($ws->connections as $val) { $ws->push($val, '{"user":"'.$frame->fd.'", "message":"'.$frame->data.'"}'); } }); // websocket $ws->on("close", function ($ws, $fd) { $link = link_redis(); $link->sRem("test_chat", $fd); echo "client-{$fd} is closed
"; }); $ws->start();

좋은 웹페이지 즐겨찾기