[php] Start Using HTML5 WebSockets Today With a PHP Server  지금 PHP 서버에서 HTML5 WebSocket 사용 시작

HTML5의 흥미로운 기능 중 하나는 AJAX 요청을 사용하지 않고 서버와 통신할 수 있는 WebSocket입니다. 이 자습서에서는 PHP에서 WebSocket 서버를 실행한 다음 WebSocket 프로토콜을 통해 메시지를 보내고 받는 클라이언트를 빌드하는 프로세스를 검토합니다.

One of the exciting features of HTML5 is WebSockets, which let us talk to the server without using AJAX requests. In this tutorial, we'll review the process of running a WebSocket server in PHP, and then building a client to send and receive messages to it over the WebSocket protocol.

 

What Are WebSockets?

A WebSocket is a persistent bi-directional communication channel between a client (e.g. a browser) and a back-end service. In contrast with HTTP request/response connections, WebSockets can transport any number of protocols and provide server-to-client message delivery without polling.

What Do WebSockets Replace?

WebSockets are designed to address the limitations of traditional HTTP-based communication. Before the introduction of WebSockets, HTTP requests and responses were stateless, meaning that each request/response pair was independent of previous and subsequent requests/responses. Due to that, it was really difficult to implement real-time communication, where the server needs to push data to the client as soon as it becomes available.

WebSockets also provide advantages over older technologies such as AJAX long polling and server-sent events (SSE). WebSockets can replace long polling easily. This is an interesting concept. The client sends a request to the server, and now, rather than the server responding with data it may not have, it essentially keeps the connection open until the fresh, up-to-date data is ready to be sent. The client next receives this and sends another request. This has its benefits: decreased latency being one of them, as a connection which has already been opened does not require a new connection to be established. However, long polling isn't really a piece of fancy technology: it's also possible for a request to time out, and thus a new connection will be needed anyway.

Many AJAX applications make use of the above—this often leads to poor resource utilization.

Wouldn't it be great if the server could send data to clients who are willing to listen without some sort of pre-established connection? Welcome to the world of push technology!

Overall, WebSockets provide a more efficient and effective solution for real-time communication, and they have become really popular for building real-time web applications.

Install the Ratchet WebSockets Library

Ratchet is a PHP library which enables building real-time, bi-directional, and event-driven applications with WebSockets. Today, we'll use this library to implement the WebSockets server.

To install the Ratchet WebSockets library, you need to use Composer, which is a dependency manager for PHP. Here are the steps to install Ratchet using Composer.

I assume that Composer is already installed on your system. With that in place, you can use the following Composer command to install the Ratchet library.

1
$composer require cboden/ratchet

Upon successful installation, it should create the following composer.json file.

1
{
2
    "require": {
3
        "cboden/ratchet": "^0.4.4"
4
    }
5
}

So we've now installed the Ratchet WebSockets library successfully.

Create the WebSockets Server

In this section, we'll see how to create a WebSockets server in PHP.

Create the server.php file with the following contents.

1
<?php
2
use Ratchet\MessageComponentInterface;
3
use Ratchet\ConnectionInterface;
4
use Ratchet\Server\IoServer;
5
use Ratchet\Http\HttpServer;
6
use Ratchet\WebSocket\WsServer;
7
 
8
require __DIR__ . '/vendor/autoload.php';
9
 
10
class WebSocketsServer implements MessageComponentInterface {
11
    protected $clients;
12
 
13
    public function __construct() {
14
        $this->clients = new \SplObjectStorage;
15
    }
16
 
17
    public function onOpen(ConnectionInterface $conn) {
18
        $this->clients->attach($conn);
19
        echo "New connection! ({$conn->resourceId})\n";
20
    }
21
 
22
    public function onMessage(ConnectionInterface $from, $msg) {
23
        foreach ($this->clients as $client) {
24
            if ($from !== $client) {
25
                $client->send($msg);
26
            }
27
        }
28
    }
29
 
30
    public function onClose(ConnectionInterface $conn) {
31
        $this->clients->detach($conn);
32
        echo "Connection {$conn->resourceId} has disconnected\n";
33
    }
34
 
35
    public function onError(ConnectionInterface $conn, \Exception $e) {
36
        echo "An error has occurred: {$e->getMessage()}\n";
37
        $conn->close();
38
    }
39
}
40
 
41
$server = IoServer::factory(
42
    new HttpServer(
43
        new WsServer(
44
            new WebSocketsServer()
45
        )
46
    ),
47
    8089
48
);
49
 
50
$server->run();

First of all, we've defined  a WebSocketsServer class, which implements the MessageComponentInterface interface, which provides the necessary callback functions for handling WebSocket events like connections, messages, and disconnections.

 

Our code then creates a new IoServer instance, which is the main entry point for running a WebSocket server. Finally, it starts the server by calling the run() method of the $server object.

WebSockets Events

WebSockets is an event-driven protocol. Let's quickly go through each event defined in the WebSocketsServer class.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

  • onOpen(ConnectionInterface $conn): triggered when a new client connects to the WebSocket server. The $conn parameter holds the connection object of the new client. In this method, we've added connections to the $clients storage object.
  • onMessage(ConnectionInterface $from, $msg): one of the most important events. It's triggered when any client sends a message from the client side to the WebSocket server. The $from parameter holds the connection object of the client who sent the message, and $msg is the message content. Also, we loop through all the clients in the $clients storage object and send the message to all clients except the sender client.

  • onClose(ConnectionInterface $conn): triggered when any client disconnects from the WebSocket server. The $conn parameter holds the connection object of the client. In this method, we've removed the connection from the $clients storage object.

  • onError(ConnectionInterface $conn, \Exception $e): triggered when an error occurs on the WebSocket server. The $conn parameter holds the connection object of the client where the error occurred, and $e is the error object.

Starting the Server

To start the WebSockets server, go ahead and run the following command on the command line.

1
$php server.php

Now, our web server is running successfully on port 8089. You can confirm this by running the following command in another tab, and it should provide the output as shown in the following snippet.

1
$telnet localhost 8089
2
Trying 127.0.0.1...
3
Connected to localhost.
4
Escape character is '^]'.

Implement the WebSockets Client

In this section, we'll build an HTML page which connects to the WebSockets server using JavaScript.

Create the client.php file with the following contents.

1
<!DOCTYPE html>
2
<html>
3
<head>
4
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
5
<title>WebSockets Client</title>
6
</head>
7
<body>
8
    <div id="wrapper">
9
        <div id="container">
10
            <h1>WebSockets Client</h1>
11
            <div id="chatLog">
12
            </div><!-- #chatLog -->
13
            <p id="examples">e.g. try 'hi', 'name', 'age', 'today'</p>
14
            <input id="text" type="text" />
15
            <button id="disconnect">Disconnect</button>
16
        </div><!-- #container -->
17
    </div>
18
 
19
    <script>
20
    $(document).ready(function() {
21
      if (!("WebSocket" in window)) {
22
          $('#chatLog, input, button, #examples').fadeOut("fast");
23
          $('<p>Oh no, you need a browser that supports WebSockets. How about <a href="https://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
24
      } else {
25
          //The user has WebSockets 
26
          connect();
27
          function connect(){
28
              var socket;
29
              var host = "ws://localhost:8089";
30
              try{
31
                  var socket = new WebSocket(host);
32
                  message('<p class="event">Socket Status: '+socket.readyState);
33
 
34
                  socket.onopen = function(){
35
                      message('<p class="event">Socket Status: '+socket.readyState+' (open)');
36
                  }
37
 
38
                  socket.onmessage = function(msg){
39
                 	 message('<p class="message">Received: '+msg.data);
40
                  }
41
 
42
                  socket.onclose = function(){
43
                  	message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
44
                  }			
45
              } catch(exception){
46
                 message('<p>Error'+exception);
47
              }
48
 
49
              function send(){
50
                  var text = $('#text').val();
51
 
52
                  if(text==""){
53
                      message('<p class="warning">Please enter a message');
54
                      return ;
55
                  }
56
 
57
                  try{
58
                      socket.send(text);
59
                      message('<p class="event">Sent: '+text)
60
                  } catch(exception){
61
                     message('<p class="warning">');
62
                  }
63
 
64
                  $('#text').val("");
65
              }
66
 
67
              function message(msg){
68
                $('#chatLog').append(msg+'</p>');
69
              }
70
 
71
              $('#text').keypress(function(event) {
72
                  if (event.keyCode == '13') {
73
                    send();
74
                  }
75
              });	
76
 
77
              $('#disconnect').click(function(){
78
                 socket.close();
79
              });
80
          }//End connect 
81
      }//End else 
82
    });
83
 
84
    </script>
85
</body>
86
</html>
87
 
88
 

Let's understand how the above code works.

Firstly, there's the HTML structure of the client-side WebSocket user interface.

After that, there's the JavaScript code which creates the WebSocket connection and implements WebSockets events. When the document is loaded, it checks if the browser supports WebSockets. If it doesn't, a message is displayed to the user to suggest switching to a browser that supports WebSockets, such as Google Chrome.

If the browser supports WebSockets, the connect() function is called, which creates a WebSocket object and connects it to the server running on ws://localhost:8089. The connect() function also defines event listeners for the WebSocket object.

Let's quickly see the event listeners that we've defined for the WebSocket object.

  • onopen: called when the connection is created. It sends a message to the chat area to indicate that the connection is open.
  • onmessage: called when a message is received from the server. It appends the received message to the chat area.
  • onclose: called when the connection is closed. It sends a message to the chat area to indicate that the connection is closed.

Apart from that, we've also built a few helper functions.

The send() function is called when a user enters a message and hits the Enter button. It sends the message to the server using the WebSocket object and appends the sent message to the chat area. The message() function is called to append messages to the chat area. Finally, the Disconnect button calls the close() function of the WebSocket object to close the connection.

How to Test the App

As we discussed earlier, go ahead and run the following command on the command prompt to start the WebSockets server.

1
$php server.php

Next, open http://localhost/client.php in a few different tabs. When the page loads, a WebSocket connection will be opened. So for example, if you've opened this URL in three different tabs, there will be three WebSocket client connections.

Now, when you enter the message and press Enter in one tab, the same message will be broadcast to other tabs as well by the WebSockets server. You can click on the Disconnect button to close the WebSocket connection.

So that's how you can use WebSockets in PHP with the help of the Ratchet library.

[출처] https://code.tutsplus.com/tutorials/start-using-html5-websockets-today--net-13270

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
149 [MySQL+PHP] MySQL 접속후 데이터 가져오기 졸리운_곰 2024.04.18 0
148 [php] [xampp] xampp php 버전 폴더 (디렉토리) 별 설정 : Running multiple PHP versions on XAMPP file 졸리운_곰 2024.03.21 3
147 [php] [PHP] Laravel - PayPal 결제 모듈 연동하기 (2) - 백엔드 처리 file 졸리운_곰 2024.03.17 1
146 [php] [PHP] Laravel - PayPal 결제 모듈 연동하기 (1) file 졸리운_곰 2024.03.17 2
145 [php] PHP - Show JSON array in html table 졸리운_곰 2024.02.18 3
144 [php] php / string을 json으로 변환 한 뒤 값 가져오기 졸리운_곰 2024.02.18 1
143 [php] Low Code Web Content Server: Making Marks on the Digital Shore. An Anecdotal View. : 로우 코드 웹 콘텐츠 서버: 디지털 해안에 흔적을 남기다. 일화적인 견해. file 졸리운_곰 2024.02.18 3
142 [php] [xampp] [php] php의 mail() 함수로 구글 이메일 보내기 / XAMPP 서버 및 aws의 EC2 / php mail function to send Gmail at XAMPP and AWS EC2 not working / Username and Password not accepted. file 졸리운_곰 2023.09.12 2
141 [php] PHP / MariaDB / 데이터베이스 값 가져와서 출력하기 졸리운_곰 2023.06.22 7
» [php] Start Using HTML5 WebSockets Today With a PHP Server 지금 PHP 서버에서 HTML5 WebSocket 사용 시작 졸리운_곰 2023.05.09 4
139 [php] json_encode 유니코드 한글 깨짐 해결방법 졸리운_곰 2023.02.04 12
138 PHP 카운터 만들기-[1] 졸리운_곰 2022.07.20 15
137 PHP로 카운터 만들기 졸리운_곰 2022.07.20 19
136 How To Build A Rest API Using PHP file 졸리운_곰 2022.07.15 16
135 PHP REST API Authentication Using JWT file 졸리운_곰 2022.07.15 13
134 [PHP] JWT 구현하기 졸리운_곰 2022.07.15 599
133 [php] Coppermine PHP로 제작된 "웹 갤러리" 프로그램임. 상당히 잘 만들어진 것같아 졸리운_곰 2021.07.04 35
132 [php] imagick php 7.3 windows 설치하기 졸리운_곰 2021.07.04 50
131 [php] simple Rest API : Build a Simple REST API in PHP file 졸리운_곰 2021.05.31 20
130 [php][php 수학][php 수치해석] MathPHP - Powerful Modern Math Library for PHP file 졸리운_곰 2021.05.03 20
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED