simple chat using websocket and php socket

37

In this tutorial, we are going to create a simple chat application using WebSocket and PHP socket programming. The WebSocket is used to create a bridge to send or receive messages from the PHP chat server. In the web world, we generally use HTTP request methods to communicate between the client and server side. In this chat example, we use sockets to communicate with the server.

For establishing a socket connection between the client and the server, we use the WebSocket protocol (ws://) to specify the address of the PHP page where the WebSocket handshake is handled. After creating WebSocket there are callbacks to handle the events that occur between the client and the server during the chat process.

Creating WebSocket and Callback Event Handlers

The following script is used to create WebSocket in client side and define callback handlers to handle the different chat events. These handlers give acknowledgments about the connection state, chat messages and the errors if any. The chat message is encoded in JSON format and sent to the server on submit.

PHP Socket Programming for the Chat Application

This PHP code checks for the new socket connection request. If any of a new connection request is found, then it will accept and perform the handshake with the new socket resource. Then, it sends an acknowledgment to the client about the connectivity by sealing the encoded acknowledgment message.

It receives the socket data sent via the existing connections and unseals and decodes it to bundle the received data and send it to the chat client. The handshake, seal, unseal, send functionalities are handled by using the ChatHandler class.

and the chat handler class is

Establish Connection using Command Line

The following image shows the command line screen to establish the connection to start chatting by using this application.

Leave A Reply

Your email address will not be published.