Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[Tutorial] How to implement Ratchet Socket on cakephp 4 and make a detail demo broadcast message from server to client (Part 2)

Friday 17 November 2023
|
Read: Completed in minutes

[Tutorial] How to implement Ratchet Socket on cakephp 4 and make a detail demo broadcast message from server to client (Part 2)

On the first part i just introduce a Ratchet Server using in Cakephp 4. on the previous part i will try to continue make a client demo connect with RatchetServer in client side.

How to implement Ratchet Socket on cakephp 4 and make a detail demo broadcast message from server to client (Part 2)



How to implement Ratchet Socket on cakephp 4 and make a detail demo broadcast message from server to client (Part 2)  - Zidane - Webzone Tech Tips

 

Our server socket with below link: ws://localhost:8080

We have sent command with token + cmd to server.

const joinCommand = {

    token: 'abcxya',

    cmd: 'SEND_JOIN',

with support send command to server.


1. WebSocket Connection Setup:
    * The code establishes a WebSocket connection to a server running on ws://localhost:8080.
    * The WebSocket object is created, and event handlers are defined for various WebSocket events such as onopen, onmessage, onclose, and onerror.
    * The onopen event handler logs a message indicating a successful connection and sends a join command to the server by sending a JSON string.
    * The onmessage event handler receives messages from the server, parses them as JSON, and performs different actions based on the message type.


2. HTML Structure:
    * The HTML structure consists of a <div> element with the class "panel" that contains various child elements.
    * The first child <div> contains a <label> element with an empty id attribute. Its purpose is to display a welcome message, but in the given code, the message is not set.
    * The second child <div> contains a <label> element with the id attribute set to "result". This element will display the content of certain messages received from the server.
    * The third child <div> contains a <button> element with the id attribute set to "broadcast". This button triggers the sendChatMessage() function when clicked.


3. JavaScript Functionality:
    * The sendChatMessage() function is called when the "broadcast" button is clicked. It sends a chat message to the server by constructing a JSON object and sending it as a string via the WebSocket connection.
    * The onmessage event handler processes the received messages based on their type. If the type is "SEND_JOIN," "BROADCAST_LOCK_SINGLE_ACCOUNT," or "BROADCAST_LOGIN," it logs the corresponding message content and updates the result label's text content.
    * If the received message type is "error," the event handler logs the message content as an error.
    * The onclose and onerror event handlers log messages indicating a disconnection or an error with the WebSocket connection, respectively.


Here is full source code for you reference.

<html>
<head>
<script>
// Create a WebSocket connection
const socket = new WebSocket('ws://localhost:
8080');

// Event handler for successful connection
socket.onopen = function(event) {
console.log('Connected to the WebSocket server');

// Send a join command to join a room
const joinCommand = {
token: '
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9',
cmd: 'SEND_JOIN',
};
socket.send(JSON.stringify(joinCommand));
};

// Event handler for incoming messages
socket.onmessage = function(event) {

if (event.data.includes('Access-Control')) {
return;
}

const message = JSON.parse(event.data);
console.log(message)
// Handle the message based on its content
if (message.type === 'SEND_JOIN') {
console.log('Received a chat message:', message.content);

} else if (message.type === 'BROADCAST_LOCK_SINGLE_ACCOUNT') {
console.log('Received a chat message:', message.content);

let result = document.getElementById('result');
result.textContent = message.content

} else if (message.type === 'BROADCAST_LOGIN') {
console.log('Received a chat message:', message.content);

let result = document.getElementById('result');
result.textContent = message.content

}

else if (message.type === 'error') {
console.log('Received an message:', message.content);
}
};

// Event handler for connection closure
socket.onclose = function(event) {
console.log('Disconnected from the WebSocket server');
};

// Event handler for connection errors
socket.onerror = function(event) {
console.error('WebSocket error:', event);
};

// Example function to send a chat message
function sendChatMessage(token) {
const chatMessage = {
cmd: 'broadcast',
language: 'zh_HK',
token: token,
};
socket.send(JSON.stringify(chatMessage));
}

window.addEventListener('load', function() {

let btn = document.getElementById('broadcast')

btn.addEventListener('click', function() {
let token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9';
sendChatMessage(token);
})
})


</script>
<style>
.panel {
border-radius: 10px;
border: 2px solid grey;
box-shadow: 5px 5px grey;
padding: 10px;
width: 300px;
display: flex;
flex-direction: column;
gap: 10px;
}
</style>
</head>
<body>
<div class="panel">

<div> <label style="color: font-size: 20px" id="welcome"> </label> </div>
<div>
<label style="color: blue; font-size: 20px" id="result"> </label>
</div>

<div>
<button id="broadcast"> Broadcast message! </button>
</div>
</div>

</body>
</html>
Thank you for reading this post. I hope you found it helpful and easy to follow. If you have any feedback or questions about How to implement Ratchet Socket on cakephp 4 and make a detail demo broadcast message from server to client (Part 2) , please share them in the comments below. I would love to hear from you and discuss this topic further
✋✋✋✋  Webzone Tech Tips, all things Tech Tips for web development  - I am Zidane, See you next time soon ✋✋✋✋

🙇🏼 We Appreciate Your Comments and Suggestions - Webzone - all things Tech Tips web development 🙇🏼
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com