In this chapter, we will build a real-time chat application usingWebSocket. You will learn how to use the Ratchet framework to build standalone WebSocket and HTTP servers with PHP and how to connect to WebSocket servers in a JavaScript client application. We will also discuss how you can implement authentication for WebSocket applications and how to deploy them in a production environment.
In this chapter, we'll be working extensively with WebSockets. To fully understand the workings of the chat application that we're going to build, let's first have a look at how WebSockets work.
The WebSockets protocol is specified in RFC 6455 and uses HTTP as the underlying transport protocol. In contrast to the traditional request/reply paradigm, in which the client sends a request to the server, who then replies with a response message, WebSocket connections can be kept open for a long time, and both server and client can send and receive messages (or data frames) on the WebSocket.
WebSocket connections are always initiated by the client (so, typically, a user's browser). The following listing shows an example request that a browser might send to a server supporting WebSockets:
GET /chat HTTP/1.1 Host: localhost Upgrade: websocketConnection: upgrade Origin: http://localhost Sec-WebSocket-Key: de7PkO6qMKuGvUA3OQNYiw== Sec-WebSocket-Protocol: chat Sec-WebSocket-Version: 13
Just like regular HTTP requests, the request contains a request method (GET
) and a path (/chat
). The Upgrade
and Connection
headers tell the server that the client would like to upgrade the regular HTTP connection into a WebSocket connection.
The Sec-WebSocket-Key
header contains a random, base64-encoded string that uniquely identifies this single WebSocket connection. The Sec-WebSocket-Protocol
header can be used to specify a subprotocol that the client would like to use. Subprotocols can be used to further define what the communication between the server and the client should look like and are often application-specific (in our case, the chat
protocol).
When the server accepts the upgrade request, it will respond with a 101 Switching Protocols
response, as shown in the following listing:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: BKb5cchTfWayrC7SKtvK5yW413s= Sec-WebSocket-Protocol: chat
The Sec-WebSocket-Accept
header contains a hash of the Sec-WebSocket-Key
from the request (the exact hashing is specified in RFC 6455). The Sec-WebSocket-Protocol
header in the response confirms that the server understands the protocol that the client specified in its request.
After this handshake is completed, the connection will stay open and both server and client can send and receive messages from the socket.
18.116.21.152