Mad Lab
Mad Lab
Lab Code:
IV B.Tech I Semester (Regulation - R20)
Prepared by
Mrs P. Madhavi Latha
Assistant Professor
Department of CSE(CS)
LABORATO RY MANUAL
Regulation : R20
Branch : CSE-IoT
Roll Number :
SYLLABUS
8
S. No Date Name of the Experiment Page no Signature
10
11
12
13
14
15
16
17
18
Basic Multimedia programs using PHOTOSHOP.
Note: Before starting, ensure you have Adobe Photoshop installed on your computer.
Introduction
Adobe Photoshop is a powerful graphics editing software widely used in various fields,
including graphic design, photography, digital art, web design, and more. It allows users
to manipulate and enhance images using a wide range of tools and features. Here are
some steps and features commonly used in Photoshop:
Launch Photoshop and go to "File" > "New" to create a new document with custom
dimensions and settings.
Basic Navigation:
Zoom in and out of the image using the zoom tool or the keyboard shortcuts (Ctrl + +
for zoom in and Ctrl + - for zoom out on Windows.
Layers:
Photoshop works with layers, which allow you to stack and organize different elements
of your project. Layers panel is usually on the right side of the interface.
Add a new layer by clicking the "New Layer" button at the bottom of the Layers panel.
Selections:
Use selection tools like the Marquee, Lasso, or Magic Wand to select parts of an image.
Once selected, you can edit, move, or apply adjustments to the selected area.
Editing Tools:
Photoshop offers a variety of tools for retouching and editing images, such as the Brush
tool, Clone Stamp tool, Healing Brush tool, and more.
Adjustments:
Make adjustments to the colors, brightness, contrast, and other attributes of the image
using the "Image" > "Adjustments" menu or adjustment layers.
Filters:
Apply artistic effects and filters to images from the "Filter" menu.
Save your work as a PSD (Photoshop Document) to retain layers and editing
capabilities.
Export your final image in various formats (JPEG, PNG, etc.) via "File" > "Export" or "Save
As."
Experiment 01. Write a program to visualize a given image in different forms using features
like brightness, contrast, blur etc.
Step 1. Open Photoshop: Launch Adobe Photoshop and open the image you want to
visualize.
Drag the "Brightness" slider to adjust the overall brightness of the image.
Still in the "Brightness/Contrast" dialog box, use the "Contrast" slider to increase or
decrease the image's contrast.
Go to "Filter" > "Blur" and choose the type of blur you want to apply (e.g., Gaussian
Blur, Motion Blur, etc.).
Adjust the blur settings, such as radius or angle, to control the intensity and direction
of the blur effect.
After applying the desired adjustments, save the image with a new name to preserve
the original image.
Step 6. Export: your final image in various formats (JPEG, PNG, etc.) via "File" > "Export"
or "Save As."
Practise: Using Photoshop's graphical interface, you can visually experiment with
different adjustments and see real-time changes in the image. Photoshop provides a
wide range of tools and features that allow you to enhance, manipulate, and visualize
images creatively.
Experiment 02. Write a program to design a visiting card containing at least one Graphic and
Text information.
Step 1. Open Photoshop: Launch Adobe Photoshop and create a new document for
the visiting card.
Step 2 . Set the width and height for the visiting card (standard visiting card size is 3.5
inches by 2 inches, but you can customize it).
To fill the background with a color, select the "Paint Bucket Tool" from the toolbar,
choose the desired color from the color picker, and click on the canvas to fill it.
To add a background image, go to "File" > "Place Embedded" and choose the image
you want to use as the background.
Import the graphic you want to use on the visiting card. You can use an image, logo,
icon, or any other graphic element.
Go to "File" > "Place Embedded" and choose the graphic file you want to add.
Click on the canvas to create a text box, then type the text information you want to
include on the visiting card (e.g., name, designation, contact details, etc.).
Use the options in the top toolbar to set the font, font size, alignment, color, and other
text properties.
Arrange the graphic and text elements on the visiting card, ensuring they are visually
balanced and aesthetically pleasing.
You can use the "Move Tool" to drag and position the elements, and the "Transform"
controls to resize, rotate, or skew them.
Once you are satisfied with the design, save your work as a Photoshop Document (PSD)
to retain the layers and editing capabilities.
To export the final visiting card for print or sharing, go to "File" > "Export" > "Export
As" and choose the desired format (e.g., JPEG or PNG).
Step 8. Print:
If you're planning to print the visiting card, make sure you set the document's resolution
to at least 300 pixels/inch (as mentioned earlier).
Save a copy of the visiting card in the appropriate resolution and color mode suitable
for print.
Experiment 03. Write a program to prepare a cover page for any book in your subject area.
• Prepare a cover page for a book in your subject area using graphic design
software like Adobe Photoshop. The subject area can vary, such as science,
literature, history, technology, etc.
Here's a basic guide to get you started:
Step1. Define the Theme: Decide on the theme and tone of the book cover. Consider
the subject area and the intended audience. Choose colors, images, and typography
that reflect the content and style of the book.
Step 2. Create a New Document: Open Adobe Photoshop and create a new document
for the book cover.
Set the dimensions based on the book's physical size or the requirements of the
publishing platform.
Choose a background color or image that complements the theme of the book. You
can use relevant stock images or illustrations that match the subject area.
Use layers to manage the elements and place the images on the canvas.
Use the "Type Tool" to add the book's title, subtitle (if any), and author name.
Experiment with different fonts and text styles to find a combination that fits the theme
and is easy to read.
Add design elements such as lines, shapes, or decorative elements to enhance the visual
appeal. Incorporate relevant icons or symbols related to the subject area to add visual
interest.
Ensure the text is well-placed and doesn't interfere with important elements of the
cover.
Export the cover as a high-resolution image (e.g., JPEG or PNG) for print or digital use.
Experiment 04. Write a program to use appropriate tools from the tool box to cut the objects
from three files (F1.jpg, F2.jpg, F3.jpg). Organize them in a single file and apply feather effects.
Step 1. Open Photoshop: Launch Adobe Photoshop and open the three image files:
"F1.jpg," "F2.jpg," and "F3.jpg."
Go to "File" > "Open" and select the first image file ("F1.jpg").
Repeat the same process for the other two images ("F2.jpg" and "F3.jpg").
Step 2. Select and Cut Objects: Use appropriate tools from the toolbox to select and
cut the objects from each image:
Use the "Marquee Tool" (M) or "Lasso Tool" (L) to make selections around the objects
you want to cut.
Once the selection is made, go to "Edit" > "Cut" or use the keyboard shortcut (Ctrl + X
or Command + X for Mac) to remove the selected portion from each image.
Create a new document in Photoshop to combine the cut objects from the three images
into a single file.
Go to "File" > "New" and set the dimensions and resolution for the new document.
Use the "Move Tool" (V) to drag and drop the cut objects from each image onto the
new document.
Go to "Select" > "Modify" > "Feather" and set the feather radius (e.g., 10 pixels).
Save the final combined image with feather effects as a Photoshop Document (PSD) to
retain editing capabilities.
If you want to export the image for other purposes, go to "File" > "Save As" and choose
the desired format (e.g., JPEG or PNG).
Multimedia Programs developed using FLASH
Adobe Flash was a popular multimedia platform used for creating interactive animations,
games, websites, and applications. However, Adobe officially discontinued Flash at the end of
2020, and many modern web browsers have dropped support for it due to security and
performance concerns. As a result, Flash-based content is no longer widely used on the
internet.
Before its discontinuation, Flash was widely used for various multimedia programs and
projects. Some examples of multimedia programs developed using Flash include:
Flash Animations: Flash was widely used to create interactive and visually appealing
animations for web banners, advertisements, educational content, and entertainment
purposes.
Flash Games: Flash games were one of the most popular uses of the platform. Many online
games, including casual and complex ones, were created using Flash.
Interactive Websites: Flash allowed developers to build interactive and visually rich websites
with animated elements, interactive menus, and multimedia content.
eLearning Modules: Flash was used to create interactive eLearning modules, tutorials, and
presentations with multimedia elements, quizzes, and interactive exercises.
Flash-based Video Players: Before HTML5 video became widely supported, Flash was
commonly used for embedding video players on websites.
Rich Media Advertisements: Flash was popular for creating rich media ads that combined
animations, video, and interactive elements to engage users.
Web Applications: Flash was used to develop web applications, such as online calculators,
data visualizations, and interactive tools.
While Flash is no longer recommended for new projects due to its end-of-life status, modern
web development technologies like HTML5, CSS, and JavaScript have taken its place. These
technologies provide better performance, security, and compatibility across devices, making
them the standard for creating multimedia content on the web.
05. Write a Program to perform motion twinning operation using flash.
Step 2: Import the motion sequences you want to twin into the Flash project. You can
either create the motion sequences within Flash or import them from external sources.
Step 3: Organize the motion sequences on different layers in the timeline. Ensure
each motion sequence occupies a separate layer and align them correctly.
Step 4: Create a new layer above the motion sequences' layers and label it as
"Tween."
Step 5: Select the first frame of the "Tween" layer and create a classic tween between
the first frame of the first motion sequence and the first frame of the second motion
sequence. To do this, right-click on the "Tween" layer's first frame and choose "Create
Classic Tween."
Step 6: Now, select the last frame of the "Tween" layer and create another classic
tween between the last frame of the first motion sequence and the last frame of the
second motion sequence.
Step 7: Adjust the easing and timing of the tweens to control the blending or
transition between the two motion sequences. You can do this by selecting the classic
tween on the "Tween" layer and modifying the tween's properties in the Properties
panel.
Step 8: Preview the animation to see how the motion twinning operation works. You
can do this by clicking on "Control" > "Test Movie" to view the animation.
Step 2: Select the "Oval Tool" (O) from the toolbar and draw a large circle to
represent the wheel's outer rim. Hold the "Shift" key while drawing to maintain a
perfect circle.
Step 3: Draw a smaller circle inside the previous one to represent the wheel's inner
rim. The size of the inner circle will determine the thickness of the wheel.
Step 5: Draw a straight line from the center of the wheel (intersection of the two
circles) towards the outer rim. This line will serve as one of the spokes.
Step 6: Press "Ctrl + D" (Windows) or "Cmd + D" (Mac) to duplicate the line.
Step 7: Rotate the duplicated line to position it at the next spoke's location. You can
do this by selecting the duplicated line and using the rotation handle at the top of the
line.
Step 8: Repeat steps 6 and 7 until you have created 24 spokes evenly spaced around
the wheel's center.
Step 9: To create a more visually appealing design, you can select all the spokes and
adjust their color and thickness using the "Properties" panel.
Step 10: You can also add a small circle or other decorative elements at the center of
the wheel to complete the design.
Step 11: Preview the animation by clicking on "Control" > "Test Movie" to view the
wheel with 24 spokes.
07. Write a Program to change and object shape using a shape twinning concept.
Step 2: Select the "Oval Tool" (O) from the toolbar and draw a shape on the stage.
For this example, we'll draw a circle.
Step 3: Right-click on the circle and choose "Convert to Symbol" (F8). Select "Movie
Clip" as the type and give it a name (e.g., "ShapeTwinningMC").
Step 4: Create a new keyframe (F6) at a later frame on the timeline (where you want
the shape twinning animation to end).
Step 5: Select the circle in the new keyframe, right-click, and choose "Convert to
Symbol" (F8) again. Select "Movie Clip" as the type and give it a different name (e.g.,
"ShapeTwinningEndMC").
Step 6: Double-click the first keyframe (the circle on the main timeline) to enter the
Movie Clip's timeline.
Step 7: Use the "Selection Tool" (V) to modify the shape of the circle. For example,
you can use the "Subselection Tool" (A) to drag the points and create a different
shape.
Step 8: Right-click on the frame between the first and second keyframe (on the same
layer) and choose "Create Shape Tween."
Step 10: Use the "Selection Tool" (V) to modify the shape of the circle. Create a
different shape from the one in the first keyframe.
Step 11: Right-click on the frame between the second and third keyframe (on the
same layer) and choose "Create Shape Tween."
Step 12: Return to the main timeline by clicking the "Scene 1" button at the top of the
screen.
Step 13: Drag and drop an instance of "ShapeTwinningEndMC" from the Library onto
the stage.
Step 14: Test the movie (Ctrl + Enter or Cmd + Enter for Mac) to see the shape
twinning animation.
Step 2: Design the e-card visuals, including the background, images, and text
elements. You can use the drawing tools, import images, and add text fields.
Step 3: Create any additional elements you want to animate, such as snowflakes, stars,
or moving objects.
Adjust the position, size, rotation, or other properties of the element to create the
animation. Flash will automatically create a smooth animation between the keyframes.
Step 5: Add more animations as needed for other elements in the e-card.
Step 6: If you want background music, import an audio file to your library and place it
on the timeline. Sync the music with the animations by extending or shortening the
audio layer.
Step 7: Test the animation by clicking "Control" > "Test Movie" or pressing "Ctrl +
Enter" (Windows) or "Cmd + Enter" (Mac). This will preview the animated e-card.
Step 8: If you are satisfied with the animation, publish the e-card:
If the output format is SWF, you can share the SWF file directly.
If the output format is HTML, you'll get an HTML file along with the SWF file. Share
both files to ensure the e-card works on web browsers.
Welcome card animation
Draw a circle on the stage. This will represent the full moon.
Convert the circle to a symbol by right-clicking on it and choosing "Convert to
Symbol" (F8). Select "Movie Clip" as the type and give it a name (e.g., "MoonMC").
Step 4: Select the circle in the new keyframe, right-click, and choose "Convert to
Symbol" (F8) again. Select "Movie Clip" as the type and give it a different name (e.g.,
"GrowingMoonMC").
Step 5: Double-click the first keyframe (the full moon shape on the main timeline) to
enter the Movie Clip's timeline.
Step 6: Modify the moon shape to represent a partially visible moon (e.g., crescent
shape). You can use the "Selection Tool" (V) or "Subselection Tool" (A) to reshape the
circle.
Step 7: Right-click on the frame between the first and second keyframe (on the same
layer) and choose "Create Motion Tween."
Step 10: Right-click on the frame between the second and third keyframe (on the
same layer) and choose "Create Motion Tween."
Step 11: Return to the main timeline by clicking the "Scene 1" button at the top of the
screen.
Step 12: Drag and drop an instance of "GrowingMoonMC" from the Library onto the
stage.
Step 13: Test the movie (Ctrl + Enter or Cmd + Enter for Mac) to see the growing
moon animation.
Adobe Flash will automatically create motion tweens between the keyframes,
smoothly transitioning the moon shape from the full moon to the crescent shape and
back to the full moon. You can adjust the timing and the shape of the crescent in the
"GrowingMoonMC" timeline to control the appearance of the growing moon.
Multimedia Programs developed using FLASH
Draw several rectangles on the stage, positioning them as steps. You can vary their
heights to represent the steps' varying levels.
Step 5: Arrange the steps and the ball on the stage according to your desired
animation.
Move the playhead to the frame where you want the ball to start its bounce.
Select the ball in the keyframe and position it on the first step (the lowest one).
Move the playhead a few frames forward and press F6 again to insert another
keyframe.
Select the ball in the new keyframe and position it above the step, simulating the ball
being in the air.
Create a motion tween between the two keyframes by right-clicking on any frame
between them and choosing "Create Motion Tween."
Adjust the "Easing" option to give the ball a bouncing motion. You can experiment
with different easing types to achieve the desired effect.
Step 8: Repeat the above steps for additional bounces or to move the ball to higher
steps.
Step 9: Return to the main timeline by clicking the "Scene 1" button at the top of the
screen.
Step 10: Test the movie (Ctrl + Enter or Cmd + Enter for Mac) to see the ball bouncing
on the steps.
Adobe Flash will automatically create the bouncing animation based on the motion
tweens you created. The easing options in the "Motion Editor" panel will determine
the smoothness and impact of the bouncing motion.
Output:
11. Write a Program to simulate a ball hitting another ball.
Draw a circle on the stage. This will represent the first ball.
Draw another circle on the stage. This will represent the second ball (the one getting
hit).
Step 4: Arrange the two ball symbols on the stage in a way that they are close
enough to interact with each other.
Move the playhead to the frame where you want the collision to occur.
Select the ball in the keyframe and adjust its position or scale to simulate the collision
with the second ball (e.g., make it smaller as if it is getting hit).
Create a motion tween between the two keyframes by right-clicking on any frame
between them and choosing "Create Motion Tween."
Step 6: Optionally, you can add additional frames to show the first ball's movement
after the collision, as if it is bouncing off the second ball.
Step 7: Return to the main timeline by clicking the "Scene 1" button at the top of the
screen.
Step 8: Test the movie (Ctrl + Enter or Cmd + Enter for Mac) to see the simulation of
the ball hitting another ball.
Adobe Flash will automatically create the animation based on the motion tweens you
created. The motion tween between the two keyframes will simulate the first ball
colliding with the second ball. You can adjust the position, size, and number of frames
to control the appearance and duration of the collision.
Output :
12. Write a Program to change a circle into a square using Flash.
Draw a square on the stage, positioned in the same location as the circle.
Move the playhead to the frame where you want the transformation to start (e.g., the
first frame).
In the "Properties" panel, click on the "Color Effect" dropdown and choose "Alpha."
Step 6: Move the playhead a few frames forward (e.g., 20 frames) and press F6 again
to insert another keyframe.
Step 7: In this new keyframe, hide the circle and reveal the square:
In the "Properties" panel, set the alpha value of the circle to 0%.
Step 8: Create a motion tween between the two keyframes by right-clicking on any
frame between them and choosing "Create Motion Tween."
Step 9: Return to the main timeline by clicking the "Scene 1" button at the top of the
screen.
Step 10: Test the movie (Ctrl + Enter or Cmd + Enter for Mac) to see the circle change
into a square.
Adobe Flash will automatically create the animation based on the motion tween you
created. The motion tween between the two keyframes will transform the circle into a
square, making the circle invisible and revealing the square.
Output:
ADOBE FLEX & AJAX
Adobe Flex was a popular framework for building rich internet applications (RIAs) using Adobe
Flash. However, as of my last knowledge update in September 2021, Adobe officially ended
support and development of Adobe Flex. Adobe recommended transitioning to HTML5 and
modern web development technologies.
If you're looking to create web applications and want to use a framework similar to Adobe Flex,
you should consider alternatives like: Adobe flash Builder or
Apache Flex (FlexJS): Apache Flex is an open-source project that continues to provide tools and
libraries for building cross-platform applications using ActionScript and MXML. It supports both
SWF-based (Flash) and HTML/JS-based output. You can find more information about Apache
Flex at https://flex.apache.org/.
HTML5 and CSS3: You can build interactive and responsive web applications using standard
HTML5 and CSS3, along with JavaScript for interactivity. HTML5 provides many features for
multimedia and interactivity without the need for Flash.
To write and run programs using these technologies, you would typically use code editors or
integrated development environments (IDEs) like Visual Studio Code, WebStorm, or any other of
your choice.
1
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600">
fontSize="24"
horizontalCenter="0"
Build and run the Flex application from your development environment.
Output:
14. create a flex project using flash builder IDE to run hello world application.
To create a Flex project using Adobe Flash Builder IDE and run a "Hello World" application,
follow these steps:
2
• Choose the application type. For a basic "Hello World" example, select "Desktop
(runs in Adobe Flash Player)" as the application type.
• Select the Flex SDK version (e.g., Apache Flex 4.x or a version you prefer).
• Set the default package name (e.g., "com.example.helloworld").
• Choose a suitable location for your project on your file system.
• Click "Next."
4. Configure the Main Application File:
• In the next screen, you can set the main application file. By default, it creates an
MXML file with the same name as your project (e.g., "HelloWorldFlex.mxml").
You can leave this as is.
• Click "Finish."
5. Edit the MXML File:
• In the Flash Builder workspace, locate the "HelloWorldFlex.mxml" file under the
"src" folder.
• Open this file and replace its content with the following code for a basic "Hello
World" application:
<fx:Script>
<![CDATA[
protected function init():void
{
// You can add any initialization code here
}
]]>
</fx:Script>
</s:Application>
6. Run the Application:
• Save the MXML file.
• Right-click on the project folder in the "Package Explorer" on the left.
• Select "Run As > Flex Application."
7. View Your "Hello World" Application:
• A new window should open with your "Hello World" application displayed in the
center.
3
Output:
15. Implement an AJAX program to fetch RSS feeds from a well-known RSS feed site. Provide a
scrolling display of latest news on your page. You can use xparser.js if you like.
To implement an AJAX program to fetch RSS feeds and display the latest news on
your web page, you can use JavaScript along with a library like xparser.js to simplify
the RSS parsing process. Here are the steps to create such a web page:
1. HTML Structure : Start by creating the HTML structure for your web page. You
will need a container to display the latest news, and a button to trigger the
RSS feed retrieval. Here's a basic HTML structure:
<ul id="news-list"></ul>
<script src="xparser.js"></script>
<script src="script.js"></script>
</body> </html>
4
2. JavaScript (script.js): Create a JavaScript file (e.g., script.js) to handle the AJAX
request, parse the RSS feed, and display the latest news. Make sure you have
included the xparser.js library in your project directory.
document.addEventListener('DOMContentLoaded', function() {
const feedURL = 'https://example.com/rss-feed-url'; // Replace with the actual RSS
feed URL
fetchButton.addEventListener('click', function() {
fetch(feedURL)
.then(response => response.text())
.then(data => {
const parser = new XParser();
parser.load(data);
5
4. xparser.js: Ensure that you have a copy of the xparser.js library in the same
directory as your HTML file. You can download it from the internet or use a
CDN to include it in your project.
5. Testing: Open the HTML file in a web browser and click the "Fetch News"
button. The JavaScript code will make an AJAX request to fetch the RSS feed,
parse it using xparser.js, and display the latest news items on your page.
6
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>
<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
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).
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
app.use(bodyParser.json());
app.use(express.static('public'));
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
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
});
}
</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.
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.
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:
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)
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.
Now, let's write the client-side code in HTML and JavaScript to allow the user
to search for cricket players by country.
<div id="error-message"></div>
<script>
function searchPlayers() {
const country = document.getElementById('country').value.trim();
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>
`;
});
</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
bash
Copy code
python server.py