Socket.io Chat
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.io Chat</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
#messages {
border: 1px solid #ddd;
padding: 10px;
height: 300px;
overflow-y: scroll;
margin-bottom: 10px;
}
#message-form {
display: flex;
gap: 10px;
}
</style>
</head>
<body>
<h1>Socket.io Chat</h1>
<div id="messages"></div>
<form id="message-form">
<input id="message-input" autocomplete="off" placeholder="Type your message..." />
<button>Send</button>
</form>
<!-- Include Socket.io client library -->
<script src="/socket.io/socket.io.js"></script>
<script>
// Step 2: Initialize the Socket.io client
const socket = io();
// Step 3: Handle form submission
document.getElementById('message-form').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent page refresh
const messageInput = document.getElementById('message-input');
const message = messageInput.value;
// Step 4: Send the message to the server
socket.emit('chat message', message);
// Clear the input field
messageInput.value = '';
});
// Step 5: Handle incoming messages
socket.on('chat message', function(msg) {
// Create a new message element
const messageElement = document.createElement('div');
messageElement.textContent = msg;
// Add the message to the messages div
document.getElementById('messages').appendChild(messageElement);
// Scroll to the bottom of the messages div
const messagesDiv = document.getElementById('messages');
messagesDiv.scrollTop = messagesDiv.scrollHeight;
});
</script>
</body>
</html>
Breakdown of the index.html
File
1. HTML Boilerplate
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.io Chat</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
#messages {
border: 1px solid #ddd;
padding: 10px;
height: 300px;
overflow-y: scroll;
margin-bottom: 10px;
}
#message-form {
display: flex;
gap: 10px;
}
</style>
</head>
<body>
<h1>Socket.io Chat</h1>
<div id="messages"></div>
<form id="message-form">
<input id="message-input" autocomplete="off" placeholder="Type your message..." />
<button>Send</button>
</form>
Explanation:
<!DOCTYPE html>
: Declares the document type and version of HTML.<html lang="en">
: The root element of the HTML document with a language attribute.<head>
: Contains metadata and links to stylesheets or scripts.<meta charset="UTF-8">
: Sets the character encoding to UTF-8.<meta name="viewport" content="width=device-width, initial-scale=1.0">
: Ensures the page scales correctly on different devices.<title>Socket.io Chat</title>
: Sets the title of the web page.<style>
: Contains internal CSS for styling the page.body
: Sets the font and padding for the body of the page.#messages
: Styles the message display area with a border, padding, and scrolling.#message-form
: Styles the form with a flex display and gap between elements.
2. Socket.io Client Library
<!-- Include Socket.io client library -->
<script src="/socket.io/socket.io.js"></script>
Explanation:
<script src="/socket.io/socket.io.js"></script>
: Loads the Socket.io client library from the server. This script is necessary to enable WebSocket communication with the server.
3. JavaScript Code
<script>
// Step 2: Initialize the Socket.io client
const socket = io();
// Step 3: Handle form submission
document.getElementById('message-form').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent page refresh
const messageInput = document.getElementById('message-input');
const message = messageInput.value;
// Step 4: Send the message to the server
socket.emit('chat message', message);
// Clear the input field
messageInput.value = '';
});
// Step 5: Handle incoming messages
socket.on('chat message', function(msg) {
// Create a new message element
const messageElement = document.createElement('div');
messageElement.textContent = msg;
// Add the message to the messages div
document.getElementById('messages').appendChild(messageElement);
// Scroll to the bottom of the messages div
const messagesDiv = document.getElementById('messages');
messagesDiv.scrollTop = messagesDiv.scrollHeight;
});
</script>
</body>
</html>
Explanation:
- Step 2: Initialize the Socket.io client
const socket = io();
const socket = io();
: Creates a new Socket.io client instance and connects it to the server.
Step 3: Handle form submission
document.getElementById('message-form').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent page refresh
const messageInput = document.getElementById('message-input');
const message = messageInput.value;
// Step 4: Send the message to the server
socket.emit('chat message', message);
// Clear the input field
messageInput.value = '';
});
document.getElementById('message-form').addEventListener('submit', function(event) { ... })
: Adds an event listener to the form to handle the submit event.
event.preventDefault();
: Prevents the default form submission behavior (which refreshes the page).
const messageInput = document.getElementById('message-input');
: Retrieves the input field for the message.
const message = messageInput.value;
: Gets the value of the input field.
socket.emit('chat message', message);
: Sends the message to the server using the chat message
event.
messageInput.value = '';
: Clears the input field after sending the message.
Step 5: Handle incoming messages
socket.on('chat message', function(msg) {
// Create a new message element
const messageElement = document.createElement('div');
messageElement.textContent = msg;
// Add the message to the messages div
document.getElementById('messages').appendChild(messageElement);
// Scroll to the bottom of the messages div
const messagesDiv = document.getElementById('messages');
messagesDiv.scrollTop = messagesDiv.scrollHeight;
});
socket.on('chat message', function(msg) { ... })
: Adds an event listener for incomingchat message
events from the server.const messageElement = document.createElement('div');
: Creates a newdiv
element to hold the message.messageElement.textContent = msg;
: Sets the text content of the newdiv
to the received message.document.getElementById('messages').appendChild(messageElement);
: Adds the new messagediv
to the messages container.const messagesDiv = document.getElementById('messages');
: Retrieves the messages container.messagesDiv.scrollTop = messagesDiv.scrollHeight;
: Scrolls the messages container to the bottom so the latest message is visible.
host your index.html
file on a different server or domain
// Replace 'http://your-api-domain.com' with your actual API server URL
const socket = io('http://your-api-domain.com');
1. Update the Socket.io Client Initialization
When connecting to a Socket.io server hosted on a different domain, you need to specify the full URL of the server. Here’s how to update the initialization:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.io Chat</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
#messages {
border: 1px solid #ddd;
padding: 10px;
height: 300px;
overflow-y: scroll;
margin-bottom: 10px;
}
#message-form {
display: flex;
gap: 10px;
}
</style>
</head>
<body>
<h1>Socket.io Chat</h1>
<div id="messages"></div>
<form id="message-form">
<input id="message-input" autocomplete="off" placeholder="Type your message..." />
<button>Send</button>
</form>
<!-- Include Socket.io client library from CDN -->
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script>
// Initialize the Socket.io client with the server URL
const socket = io('http://your-api-domain.com');
// Handle form submission
document.getElementById('message-form').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent page refresh
const messageInput = document.getElementById('message-input');
const message = messageInput.value;
// Send the message to the server
socket.emit('chat message', message);
// Clear the input field
messageInput.value = '';
});
// Handle incoming messages
socket.on('chat message', function(msg) {
// Create a new message element
const messageElement = document.createElement('div');
messageElement.textContent = msg;
// Add the message to the messages div
document.getElementById('messages').appendChild(messageElement);
// Scroll to the bottom of the messages div
const messagesDiv = document.getElementById('messages');
messagesDiv.scrollTop = messagesDiv.scrollHeight;
});
</script>
</body>
</html>