0% found this document useful (0 votes)
26 views17 pages

Mmad

Modules and project
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views17 pages

Mmad

Modules and project
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

16.

To implement an RSS-based search feature in a multimedia application,


you can create a simple HTML page with a text box for input and a button
to perform the search. The results will be displayed as hyperlinks in a
separate <div>. Below is an example implementation using HTML,
JavaScript, and basic CSS.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>RSS Search Feature</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#results {
margin-top: 20px;
}
a{
display: block;
margin: 5px 0;
text-decoration: none;
color: blue;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>

<h1>RSS-Based Search Feature</h1>


<input type="text" id="searchQuery" placeholder="Enter search
term...">
<button id="searchButton">Search</button>

<div id="results"></div>

<script>
document.getElementById('searchButton').addEventListener('click',
function() {
const query = document.getElementById('searchQuery').value;
fetchRSSFeed(query);
});

function fetchRSSFeed(query) {
// Example RSS feed URL (you may replace it with a real one)
const rssUrl = 'https://example.com/rss-feed-url';

fetch(rssUrl)
.then(response => response.text())
.then(str => new window.DOMParser().parseFromString(str,
"text/xml"))
.then(data => {
const items = data.querySelectorAll("item");
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = ''; // Clear previous results

items.forEach(item => {
const title = item.querySelector("title").textContent;
const link = item.querySelector("link").textContent;

if (title.toLowerCase().includes(query.toLowerCase())) {
const a = document.createElement('a');
a.href = link;
a.target = '_blank';
a.textContent = title;
resultsDiv.appendChild(a);
}
});
})
.catch(err => {
console.error('Error fetching the RSS feed:', err);
});
}
</script>

</body>
</html>

Explanation

1. HTML Elements:
o A text input for entering the search query.
o A button to trigger the search.
o A <div> to display the search results as hyperlinks.
2. JavaScript:
o An event listener is added to the button to initiate the search
when clicked.
o The fetchRSSFeed function fetches the RSS feed from a
specified URL (replace with a valid RSS feed URL).
o It parses the XML response and filters items based on the
search query.
o Matching items are displayed as hyperlinks in the results
<div>.
3. Styling:
o Basic CSS is applied for readability and usability.

Notes

 Ensure you replace https://example.com/rss-feed-url with a valid


RSS feed URL.
 If the RSS feed is hosted on a different origin, you may encounter
CORS issues. In that case, consider using a proxy server or CORS-
enabled service.
 This example does not include error handling for empty input or no
results found, which you may want to add for better user experience.

17. Use the Reverse AJAX technique to build a web-based chat application.
The application is one-way browser-based. That is, we have a window in
which one user types his messages. From other other side, the second user
directly updates a file on the server(instead of a browser area).

Step 1: Server Setup (Node.js)

First, you'll need to set up a Node.js server that can handle incoming
messages and write them to a file. Here’s a simple implementation:

1. Install Node.js and Express: Make sure you have Node.js installed. You
can create a new project and install Express:

mkdir chat-app
cd chat-app
npm init -y
npm install express body-parser

2. Create server.js: Create a file named server.js:


const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();
const PORT = 3000;

app.use(bodyParser.json());
app.use(express.static('public'));

// Endpoint to receive messages


app.post('/send', (req, res) => {
const message = req.body.message;
fs.appendFile('messages.txt', message + '\n', err => {
if (err) {
return res.status(500).send('Error writing to file');
}
res.send('Message received');
});
});

// Endpoint to fetch messages


app.get('/messages', (req, res) => {
fs.readFile('messages.txt', 'utf-8', (err, data) => {
if (err) {
return res.status(500).send('Error reading file');
}
res.send(data.trim().split('\n'));
});
});

app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});

Step 2: Front-End Implementation

Create a public directory inside your project folder, then create an


index.html file within it:

3. Create public/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Chat Application</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#messages { border: 1px solid #ccc; padding: 10px; height: 300px;
overflow-y: scroll; }
input { width: 80%; }
</style>
</head>
<body>
<h1>Chat Application</h1>
<div id="messages"></div>
<input type="text" id="messageInput" placeholder="Type your
message here...">
<button id="sendButton">Send</button>

<script>
document.getElementById('sendButton').addEventListener('click',
function() {
const message = document.getElementById('messageInput').value;
if (message) {
sendMessage(message);
document.getElementById('messageInput').value = ''; // Clear
input
}
});

function sendMessage(message) {
fetch('/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message })
});
}

function fetchMessages() {
fetch('/messages')
.then(response => response.json())
.then(data => {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML = '';
data.forEach(msg => {
const msgElement = document.createElement('div');
msgElement.textContent = msg;
messagesDiv.appendChild(msgElement);
});
messagesDiv.scrollTop = messagesDiv.scrollHeight; // Auto-
scroll
});
}

setInterval(fetchMessages, 2000); // Poll every 2 seconds


</script>

</body>
</html>

Explanation

1. Server Side:
o The server listens for messages on the /send endpoint and
appends them to messages.txt.
o It can serve the contents of messages.txt on the /messages
endpoint.
2. Client Side:
o The HTML includes an input field for the user to type
messages and a button to send them.
o When the button is clicked, a POST request is made to send the
message.
o The application polls the server every 2 seconds to fetch and
display new messages.

Step 3: Run the Application

To run your application:

1.start the server


node server.js
2.Open your browser and navigate to http://localhost:3000.

Notes

 This implementation uses basic file I/O for simplicity; consider using
a database for a production application.
 Ensure you handle potential security concerns (e.g., input validation,
sanitization).
 The client-side implementation is kept simple; you can enhance the
UI with CSS or frameworks like Bootstrap or Vue.js for a better user
experience.

18.A file on a server has information about cricket players. The fields represent
name,country, matches, runs and centuries. The fields are separated by colons
(:). The front end screen has a text field in which the user can enter a country.
The server returns details of all players belonging to that country in the form of
one big JSON object. The client parses the JSON object and builds an HTML
table to print the results. Implement the server side script and the client code.

o implement the server-side and client-side code for displaying cricket players
by country in a multimedia application development lab, we can use the
combination of a backend (server-side) script in Python with Flask and frontend
(client-side) code in HTML with JavaScript. The server will return a JSON
object containing cricket player data, and the client will use this JSON data to
render an HTML table.

Server Side Code (Python using Flask)

We will use the Flask framework for building a simple API that reads player
data from a file and returns it as a JSON response.
Step 1: Install Flask

If Flask is not installed on your system, you can install it using pip:

pip install flask


Step 2: Python Code for the Server

Here's the Python script for the Flask backend:

from flask import Flask, jsonify, request


import os

app = Flask(__name__)

# Path to the file where cricket player data is stored


PLAYER_FILE = 'players.txt'

# Load player data from the file


def load_players():
players = []
if os.path.exists(PLAYER_FILE):
with open(PLAYER_FILE, 'r') as file:
for line in file:
fields = line.strip().split(':')
if len(fields) == 5:
player = {
'name': fields[0],
'country': fields[1],
'matches': int(fields[2]),
'runs': int(fields[3]),
'centuries': int(fields[4])
}
players.append(player)
return players

# Endpoint to fetch players based on country


@app.route('/players', methods=['GET'])
def get_players_by_country():
country = request.args.get('country', '').strip()
if not country:
return jsonify({"error": "Country is required"}), 400

players = load_players()
filtered_players = [player for player in players if
player['country'].lower() == country.lower()]

if not filtered_players:
return jsonify({"error": "No players found for the given country"}),
404

return jsonify(filtered_players)

if __name__ == '__main__':
app.run(debug=True)
Explanation of Server-Side Code:

1. Imports:
o Flask, jsonify, and request are imported from the Flask library to
handle the HTTP requests and responses.
2. load_players function:
o Reads the players.txt file.
o Each line is split by the colon (:) to extract the player's information:
name, country, matches, runs, and centuries.
o A list of player dictionaries is created and returned.

3. get_players_by_country function:
o Retrieves the country parameter from the query string in the URL.
o Filters players by the country.
o Returns a JSON object with the filtered players, or an error
message if no players are found.

4. Running the Server:


o The server runs on localhost:5000 by default. You can change the
host and port if needed.

Example Content for players.txt File:


Sachin Tendulkar:India:200:18426:49
Ricky Ponting:Australia:168:13704:41
Virat Kohli:India:99:7547:27
Jacques Kallis:South Africa:166:10189:45
MS Dhoni:India:90:4876:10
Steve Smith:Australia:95:7542:25

Client-Side Code (HTML + JavaScript)

Now, let's write the client-side code in HTML and JavaScript to allow the user
to search for cricket players by country.

HTML + JavaScript Code:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Cricket Players by Country</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 8px;
text-align: center;
}
#error-message {
color: red;
display: none;
}
</style>
</head>
<body>

<h1>Search Cricket Players by Country</h1>

<label for="country">Enter Country: </label>


<input type="text" id="country" placeholder="e.g. India">
<button onclick="searchPlayers()">Search</button>

<div id="error-message"></div>
<table id="players-table" style="display: none;">
<thead>
<tr>
<th>Name</th>
<th>Country</th>
<th>Matches</th>
<th>Runs</th>
<th>Centuries</th>
</tr>
</thead>
<tbody></tbody>
</table>

<script>
function searchPlayers() {
const country = document.getElementById('country').value.trim();

// Show error if country is empty


if (!country) {
alert("Please enter a country.");
return;
}

// Hide previous table and error messages


document.getElementById('players-table').style.display = 'none';
document.getElementById('error-message').style.display = 'none';
// Make an API call to the server
fetch(`/players?country=${encodeURIComponent(country)}`)
.then(response => response.json())
.then(data => {
if (data.error) {
document.getElementById('error-message').textContent =
data.error;
document.getElementById('error-message').style.display =
'block';
} else {
// Populate the table with player data
const table = document.getElementById('players-table');
const tbody = table.querySelector('tbody');
tbody.innerHTML = ''; // Clear previous table rows

data.forEach(player => {
const row = tbody.insertRow();
row.innerHTML = `
<td>${player.name}</td>
<td>${player.country}</td>
<td>${player.matches}</td>
<td>${player.runs}</td>
<td>${player.centuries}</td>
`;
});

table.style.display = 'table'; // Show the table


}
})
.catch(error => {
console.error('Error fetching player data:', error);
document.getElementById('error-message').textContent = 'An
error occurred while fetching the data.';
document.getElementById('error-message').style.display =
'block';
});
}
</script>

</body>
</html>
Explanation of the Client-Side Code:

1. HTML Structure:
o An input field is provided for the user to enter the country name.
o A button triggers the search for players based on the entered
country.
o An error message is displayed if no players are found or if an error
occurs.
o A table is used to display the results, with columns for player
name, country, matches, runs, and centuries.

2. JavaScript Functionality:
o The searchPlayers function gets the value entered in the country
input field.
o If the input is empty, an alert prompts the user to enter a country.
o The function then makes a fetch request to the /players API with
the country as a query parameter.
o If the server returns player data, it dynamically creates rows in the
HTML table.
o If there is an error (e.g., no players are found), an error message is
displayed.
o If the request fails (e.g., network issues), a generic error message is
shown.

Running the Application

1. Set Up the Server:


o Save the server code to a file named server.py.
o Place the players.txt file with player data in the same directory as
server.py.

2. Start the Flask Server: Run the Flask server with the following
command:

bash
Copy code
python server.py

3. Access the Client-Side Code:


o Open the index.html file in a browser to interact with the front-end.

4. Test the Application:


o Enter a country name (e.g., "India") in the input field and click
"Search."
o The table should display players from that country, or show an
error message if no players are found.

You might also like