Introduction to Socket.IO in PHP

  • Socket.Io Is A Popular Library That Enables Real-Time, Bidirectional Communication Between Clients (Such As Web Browsers) And Servers Over Web Sockets. It Simplifies The Process Of Building Applications That Require Instant Data Updates, Such As Chat Applications, Real-Time Dashboards, Online Gaming, And Collaborative Tools.

Socket.IO Features

  • Real-time Communication:
    • Socket.IO establishes a persistent connection between the client and server, allowing real-time data exchange without the need for frequent page reloads.
  • Event-Based Architecture
    • Communication in Socket.IO is based on events. Clients can emit events to the server, and the server can emit events to clients, enabling them to exchange data and notifications.
  • Broadcasting
    • Socket.IO allows the server to broadcast messages to all connected clients or to specific clients, enabling group communication and updates.
  • WebSocket Support
    • Socket.IO utilizes the WebSocket protocol, which allows for full-duplex communication between the client and server. This enables real-time data exchange without the overhead of traditional HTTP requests and responses.

Socket.IO Real-World Scenarios

  • Real-Time Chat Applications
    • Socket.IO is frequently used to build real-time chat applications where users can exchange messages instantly. It’s well-suited for both one-on-one conversations and group chats.
  • Real-Time Notifications
    • Websites and applications that need to provide users with real-time notifications, such as social media platforms, messaging apps, or news websites, can utilize Socket.IO to push notifications to users as they happen.
  • Live Sports and Events Updates
    • Websites and apps focused on delivering live updates for sports events, conferences, or other time-sensitive occurrences can utilize Socket.IO to keep users informed as events unfold.
  • Financial Trading Platforms
    • Real-time financial trading platforms require immediate updates on stock prices and market changes. Socket.IO can be used to deliver these updates to traders and investors in real time.
  • Live Auctions and Bidding
    • Online auction platforms can use Socket.IO to display live bids and updates during an auction, creating a dynamic and competitive atmosphere for bidders.
  • Live Customer Support
    • Online customer support chat systems can use Socket.IO to facilitate instant communication between customers and support agents, improving response times and overall user experience.

Example: Implement Real time chat application using socket.io in PHP

  • Project Structure Setup
    • Create a new project folder
    • Inside the project folder, create the following files:
      • index.php: Frontend HTML.
      • style.css: Frontend CSS.
      • script.js: Frontend JavaScript.
      • server.js: For Socket.js (server-side code).
  • Installing Required Dependencies: (go to the project root directory in Terminal)
    • Install Composer dependencies
      • composer install
    • Install Node.js (if not already installed) from nodejs.org
    • Install npm
      • Npm Is Nodejs Package Manager Which Downloads And Manage  pacakges. Install npm package if you don’t have.
      • npm install
  • Install Express.js
    • Express.js is Node.js web application backend framework building web applications and API.
    • npm install express
  • Install Socket.IO
    • npm install socket.io

Creating some files

  • index.php
<!DOCTYPE html>
<html>
    <head>
        <title>Chat App Using Socket.io</title>
        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <div class="container">
            <div class="chat-row">
                <div class="row chat-section">
                    <div class="chat-box">
                        <div class="chat-input bg-primary" id="chatInput" contenteditable=""></div>
                    </div>
                </div>
                <div class="row chat-content">
                   <ul></ul>
                </div>
            </div> 
        </div>
        <script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM=" crossorigin="anonymous"></script>
        <script src="https://cdn.socket.io/4.6.0/socket.io.min.js" integrity="sha384-c79GN5VsunZvi+Q/WObgk2in0CbZsHnjEqvFxC5DxHn9lTfNce2WW6h2pH6u/kF+" crossorigin="anonymous"></script>
        <script type="text/javascript" src="app.js"></script>
    </body>
</html>
  • style.css
 .chat-row{
    margin:50px;
}
ul{
    margin: 0;
    padding: 0;
    list-style: none;
}
ul li{
    padding: 8px;
    background: #928787;
    margin-bottom: 20px;
    border-radius: 10px;
}
ul li:nth-child(2n-2){
    background: #c3c5c5;
}
.chat-input{
    border: 1px solid lightgray;
    border-radius: 10px;
    padding: 6px 280px;
    color: #fff;
    margin-bottom: 20px;
}
  • script.js
$(function() {
    let ip_address='127.0.0.1';
    let socket_port='3000';
    let socket=io(ip_address+':'+socket_port);

    //socket.on('connection');
    let chatInput=$('#chatInput');

    chatInput.keypress(function(e){
        let message=$(this).html();
        console.log(message);
        if(e.which === 13 && !e.shiftkey){
            socket.emit('sendchatToserve',message);
            chatInput.html('');
            return false;
        }
    });

    socket.on('sendchatToclient',(message)=>{
        $('.chat-content ul').append(`<br><li>${message}</li>`);
    });
                
});

Creating Socket Server (server.js): server.js

  • Realtime chat message logic added in server.js file.
const express = require('express');

const app = express();

const server = require('http').createServer(app);

const io = require('socket.io')(server, {
	cors:{origin:'*'}
});

io.on('connection', (socket) => {
  console.log('connection');

  socket.on('sendchatToserve',(message)=>{
  	console.log('message');
  	// io.sockets.emit('sendchatToclient',message);
  	socket.broadcast.emit('sendchatToclient',message);
  });

  socket.on('disconnect',(socket) => {
  	console.log('disconnect');
  });
});

server.listen(3000,()=>{
	console.log("server is runnig");
});

Testing the application

  • For a test application, you need to start Node.js server using below command
    • node server
  • Now open your two different browsers, with your localhost URL like : http://localhost/project_name

Demo Image

You may also like

Leave a Reply