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)
Explore My Other Channel for More Cool and Valuable Insights
👉 Youtube Learn Tech Tips👉 Tiktok
👉 Facebook: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>