Beruflich Dokumente
Kultur Dokumente
CSC 409L
SYSTEM PROGRAMMING
(v. 1.0)
Student Name:
Class and Section:
Roll Number:
CGPA:
Email ID:
Submitted To:
SAIF UD DIN
SE-8(B)
5699
saifuddin.ba@gmail.com
Umar Mahmud
This lab manual has been prepared to facilitate the students of System Programming as part of Software
Engineering discipline. The manual lists experiments that are performed as part of the lab activity. The
experiments range from utilization of system services to developing processes, threads and modules.
Each experiment provides exercise question as well as question that check the knowledge and
understanding of the student. The students will be able to understand system level concepts once they
have completed this manual.
GENERAL INSTRUCTIONS
a. This is an individual based activity. Each student must have a lab manual.
b. Students are required to maintain the lab manual with them till the end of the semester.
c. All outcomes, answers to questions and illustrations must be provided in the reserved areas. If more
space is required then additional sheets may be attached.
d. It is the responsibility of the student to have the manual graded before deadlines as given by the
instructor
e. Loss of manual will result in resubmission of the complete manual.
f. Students are required to go through the experiment before coming to the lab session. Lab session
details will be given in training schedule.
g. Students must bring the manual in each lab.
h. Keep the manual neat clean and presentable.
i. Plagiarism is strictly forbidden. No credit will be given if a lab session is plagiarised and no
resubmission will be entertained.
j. Marks will be deducted for late submission.
VERSION HISTORY
Month
Update By
February 2015
AP Umar Mahmud
CSC 409L
Details
First version created with 10 experiments
Page 2
MARKS
Exp
#
Date
Conducted
1
2
3
4
5
6
7
8
9
10
Experiment Title
FILE OPERATIONS USING
WINDOWS API
FILE SYSTEMS AND
DIRECTORY LISTINGS
WINDOWS API
PROCESSES
THREAD MANAGEMENT
VIRTUAL MACHINES
MODULE PROGRAMMING I
MODULE PROGRAMMING II
SYSTEM COMMANDS AND
REGISTRY INFORMATION
SOCKETS
10
Sessional
Mid-term Exam
Terminal Exam
10
35
50
Grand Total
CSC 409L
Max.
Marks
10
10
10
10
10
10
10
10
10
100
Page 3
Marks
Obtained
Instructor
Sign
LIST OF EXPERIMENTS
EXPERIMENT 1 FILE OPERATIONS USING WINDOWS API..........................................................4
EXPERIMENT 2 FILE SYSTEMS AND DIRECTORY LISTINGS......................................................9
EXPERIMENT 3 WINDOWS API........................................................................................................16
EXPERIMENT 4 PROCESSES.............................................................................................................21
EXPERIMENT 5 THREAD MANAGEMENT.....................................................................................29
EXPERIMENT 6 VIRTUAL MACHINE..............................................................................................34
EXPERIMENT 7 MODULE PROGRAMMING I................................................................................37
EXPERIMENT 8 MODULE PROGRAMMING II...............................................................................42
EXPERIMENT 9 SYSTEM COMMANDS AND REGISTRY INFORMATION.................................45
EXPERIMENT 10 SOCKETS...............................................................................................................57
SOFTWARE REQUIREMENTS
Platform
Software Tools
Languages
Windows 7 or 8
Java
Ubuntu 11
DEV++/Borland C/Visual
Studio
GCC
C++
VM Ware
CSC 409L
Page 4
CSC 409L
Page 5
Objectives:
(a). File copying with standard C library.
2.
3.
Software Required:
(a). Visual C++/Borland C++/Dev C++
(b). Windows OS
(c). Windows System Programming Examples
Available here http://jmhartsoftware.com/WSP4_Examples.zip
4.
Computer File: A computer file is a resource for storing information, which is available to
a computer program and is usually based on some kind of durable storage. A file is
"durable" in the sense that it remains available for other programs to use after the program
that created it has finished executing. Computer files can be considered as the modern
counterpart of paper documents which traditionally are kept in office and library files, and
this is the source of the term.
5.
Creating a Random File: Create a random txt file and name it as yourname.txt. Store it in
working directory. Place any random data in this file and make its size large.
6.
File Copying with Standard C Library: Type the following code that uses C library
function: /* Chapter 1. Basic cp file copy program. C library Implementation.
Save file as copyCode.c
copyCode file1 file2: Copy file1 to file2. */
#include <stdio.h>
#include <errno.h>
#define BUF_SIZE 256
int main (int argc, char *argv [])
{
FILE *inFile, *outFile;
char rec[BUF_SIZE];
size_t bytesIn, bytesOut;
if (argc != 3) {
fprintf (stderr, "Usage of code: copyCode inputfile.txt outfile.txt\n");
return 1;
}
inFile = fopen (argv[1], "rb");
Page 6
if (inFile == NULL) {
perror (argv[1]);
return 2;
}
outFile = fopen (argv[2], "wb");
if (outFile == NULL) {
perror (argv[2]);
fclose(inFile);
return 3;
}
/* Process the input file a record at a time. */
while ((bytesIn = fread (rec, 1, BUF_SIZE, inFile)) > 0) {
bytesOut = fwrite (rec, 1, bytesIn, outFile);
if (bytesOut != bytesIn) {
perror ("Fatal write error.");
fclose(inFile); fclose(outFile);
return 4;
}
}
fclose (inFile);
fclose (outFile);
return 0;
}
7.
8.
9.
Compile and execute the code in point 6. File copyCode.exe will be generated. In
Command Prompt navigate to the working directory and issue the following command
copyCode yourname.txt output.txt
What is the outcome? (Copy & paste the output screen here).
(1
What is your understanding in the above code? How is file copying carried out using C
library?
(2
File Copying with Windows API: Type the following code that uses Windows API: /* Chapter 1. Basic cp file copy program. Win32 Implementation.
Save file as copyCodeWindow.ccopyCodeWindow file1 file2: Copy file1 to file2. */
#include <windows.h>
#include <stdio.h>
Page 7
(1
Compile and execute the code in point 6. File copyCodeWindow.exe will be generated. In
Command Prompt navigate to the working directory and issue the following
commandcopyCodeWindow yourname.txt output.txt
What is the outcome? (Copy & paste the output screen here).
8.
What is your understanding in the above code? How is file copying carried out using C
(2
Page 8
9.
library?
(1
)
10
.
11
.
Now create different files of different sizes. (e.g., 2KB, 4KB, 6KB, etc). Then improve both
codes so that time could be measures i.e., time of execution of both codes. Plot a graph that
shows the effect of file size on execution time for both codes. You may select time as a
nanosecond unit. Show the graph here with atleast 10 different sizes. What is your
conclusion?
References:
http://en.wikipedia.org/wiki/Computer_file
Page 9
(3
)
http://jmhartsoftware.com/WSP4_Examples.zip
12
.
Summary:
This experiment uses different codes for file copying. Two techniques are observed i.e.,
using C library and using Windows API. A graph is generated that shows the execution time
vs. size of file.
Page 10
Objectives:
(a). File system information
(b). Reading file systems information in java
2.
3.
Software/Language Required:
(a). NetBeans 8/Eclipse Kepler
(b). Turbo C/Visual Studio 9/Dev C++
(c). Windows OS
4.
5.
Page 11
(1)
*/
import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class FileAllocationTableExample {
public static void main(String[] args) {
System.out.println("File system roots
byFileSystemView.getFileSystemView():");
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (int i = 0; i < roots.length; i++) {
System.out.println("Root: " + roots[i]);
}
returned
Page 12
Re-execute the Java Code and connect your mobile phone as well as USB devices with
your system. Also insert a DVD/CD in the ROM. Display output here: -
6.
What is the difference in the above outputs? What kind of information was shared?
(1)
7.
(1)
Page 13
package fileallocationtableexample;
import java.nio.file.FileSystems;
/**
*@http://bits.netbeans.org/dev/javadoc/org-openidefilesystems/org/openide/filesystems/FileSystem.html
*/
public class TestFileSystem {
public static void main(String args[]){
System.out.println(FileSystems.getDefault());
}
}
What is the output? Show here? What did you understand by the code?
8.
Page 14
(1)
9.
10.
Directory Listing Using C/C++:The following code gives the directory listing using
C++.
#include <fstream>
#include <iostream>
#include <string>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
int main()
{
ifstream fin;
string dir, filepath;
int num;
DIR *dp;
struct dirent *dirp;
struct stat filestat;
cout << "dir to get files of: " << flush;
getline( cin, dir ); // gets everything the user ENTERs
dp = opendir( dir.c_str() );
if (dp == NULL)
Page 15
(1)
{
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir( dp )))
{
filepath = dir + "/" + dirp->d_name;
// If the file is a directory (or is in some way invalid) we'll skip it
if (stat( filepath.c_str(), &filestat )) continue;
if (S_ISDIR( filestat.st_mode ))
continue;
// read a single number from the file and display it
fin.open( filepath.c_str() );
if (fin >> num)
cout << filepath << ": " << num << endl;
fin.close();
}
closedir( dp );
return 0;
}
Execute this code and show the output here: -
11.
Directory Listing in Java: The following code shows the directory listing of working
directory.
package test;
import java.io.File;
public class ListFiles {
public static void main(String[] args) {
// Directory path here
String path = "."; //path name here
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
System.out.println(files);
}
}
}
}
Page 16
12.
Update both codes that shows the directory listing of a given directory in a column
format showing the File Name, File Size, and File Rights (Read only, Write Only, Both)
and Last Accessed Time and date. Show the output of both codes here and show the
execution on machine as well.
13.
References:
http://stackoverflow.com/questions/15656139/get-partition-and-volume-information?
rq=1http://en.wikipedia.org/wiki/File_system
http://bits.netbeans.org/dev/javadoc/org-openidefilesystems/org/openide/filesystems/FileSystem.html
http://www.tutorialspoint.com/java/io/file_listroots.htm
https://en.wikipedia.org/wiki/Directory_%28computing%29
https://en.wikipedia.org/wiki/File:DirectoryListing1.png
http://www.javaprogrammingforums.com/java-programming-tutorials/3-java-programcan-list-all-files-given-directory.html
http://www.cplusplus.com/forum/beginner/10292/
12.
Summary: This experiment uses different methods available in Java to access File
System Descriptions and Roots information. Furthermore, directory listing using Java
and C++ is also observed. Students are required to update both codes so that complete
directory listing is achieved.
Page 17
(3)
2.
3.
4.
5.
Objectives:
(a). Windows API
(b). WinMain()
(c). Message Loop
Time Required: 3 hrs
Software/Language Required:
(a). Turbo C/Visual Studio 9/Dev C++
(b). Windows OS
Win 32 API: The Windows API, informally WinAPI, is Microsoft's core set of application
programming interfaces (APIs) available in the Microsoft Windows operating systems. The
name Windows API collectively refers to a number of different platform implementations
that are often referred to by their own names (for example, Win32 API). Almost all
Windows programs interact with the Windows API.The Windows API (Win32) is
implemented in the C programming language and is not object-oriented. Windows 8, while
still providing the Win32 API, also provides the WinRT API which is implemented in the
C++ programming languageand is object-oriented by its design.
Directory Listing Using C/C++: Type in the following code.
(1
)
Ex
ecute this code and show the output here: -
WinMain() is windows equivalent of main() from DOS. This is where your program starts
execution. The parameters are as follows:
HINSTANCE hInstance. Handle to the programs executable module (the .exe file in
memory). It is is used for things like loading resources and any other task which is
performed on a per-module basis. A module is either the EXE or a DLL loaded into your
program.
HINSTANCE hPrevInstance. Always NULL for Win32 programs. It used to be the handle
Windows API
Page 18
6.
to the previously run instance of your program (if any) in Win16. This no longer applies. In
Win32 you ignore this parameter.
LPSTR lpCmdLine. The command line arguments as a single string. NOT including the
program name.
int nCmdShow. An integer value which may be passed to ShowWindow().
Simple Window Program: Type the following code
#include <windows.h>
const char g_szClassName[] = "myWindowClass";
// Step 4: the Window Procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam,
LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd;
MSG Msg;
//Step 1: Registering the Window Class
wc.cbSize
= sizeof(WNDCLASSEX);
wc.style
= 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon
= LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor
= LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm
= LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
// Step 2: Creating the Window
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
Windows API
Page 19
(1
)
g_szClassName,
"The title of my window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
NULL, NULL, hInstance, NULL);
if(hwnd == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// Step 3: The Message Loop
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
Execute this code and show the output here: -
7.
Step 1 - Registering Window Class: A Window Class stores information about a type of
window, including its Window Procedure which controls the window, the small and large
icons for the window, and the background color. This way, you can register a class once, and
create as many windows as you want from it, without having to specify all those attributes
over and over. Most of the attributes you set in the window class can be changed on a perwindow basis if desired. A Window Class has NOTHING to do with C++ classes.
Step 2 - Creating The Window: Once the class is registered, we can create a window with
it.
Step 3 Message Loop: This is the heart of the whole program, pretty much everything
that your program does passes through this point of control.GetMessage() gets a message
from your application's message queue. Any time the user moves the mouse, types on the
keyboard, clicks on your window's menu, messages are generated by the system and entered
into your program's message queue. By calling GetMessage() you are requesting the next
available message to be removed from the queue and returned to you for processing. If there
is no message, GetMessage() Blocks. TranslateMessage() does some additional processing
Windows API
Page 20
8.
(2
)
9.
Update the code so as that it prints the file parameters of the executable including file name,
Windows API
Page 21
(6
file size and creation date in the dialog box. Show code and output here
Windows API
Page 22
10
.
11
.
References:
http://www.winprog.org/tutorial/simple_window.html
https://en.wikipedia.org/wiki/Windows_API
http://msdn.microsoft.com/en-us/library/ff818516%28v=vs.85%29.aspx
Summary: This experiment provides examples to create a window using Win API. The use
of WinMain(), Message Loop and WinProcedure() are observed.
Windows API
Page 23
EXPERIMENT 4 PROCESSES
1.
Objectives:
(a). Creating processes in Ubuntu.
(b). Learning fork commands in Ubuntu
2.
3.
Software Required:
(a). Ubuntu/Linux and gcc compiler (already available in Ubuntu)
(b). Borland/Turbo C/Visual Studio for Windows Platform
(c). VMWare if required
(d). C language
4.
Processes
Page 24
(g). Third line runs the exe file and shows output of the program.
5.
Using getpid(): This function returns the pid of the current program. Use the following code and
write the output.
int main(){
int pid;
pid = getpid();
printf(Process ID is %d\n, pid);
return 0;
}
6.
Processes
Page 25
Outcome:
waqar@ubunte:~Desktop$ ./hello
Process Id is 4739
I is 0 . I is 399
7.
Using getppid(): This function returns the pid of the parent process.
int main(){
Processes
Page 26
int ppid;
ppid = getppid();
printf(Parent Process ID is %d\n, ppid);
return 0;
}
What is the outcome?
8.
Using fork(): fork command in Linux creates a new process by duplicating the calling process. The
new process, referred to as the child, is an exact duplicate of the calling process, referred to as the
parent.What is the outcome of the following program?
int main(){
fork();
Processes
Page 27
9.
Processes
Page 28
else{
printf(I am the parent, my process ID is %d\n, getpid());
printf(The parent process ID is %d\n, getppid());
}
return 0;
}
10. To see if the pid is same as shown in the system, Open System Monitor. Check to see if the pid is
same. Use the following code
int main(){
int pid,i;
pid = fork();
if(pid==0){
Processes
Page 29
Page 30
(3)
Page 31
int main(){
pid_t pid;
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed\n");
exit(-1);
}
else if (pid == 0) { /* child process */
printf("I am the child %d\n",pid);
execlp("/bin/ls","ls",NULL);
}
else { /* parent process */
/* parent will wait for the child to complete */
printf("I am the parent %d\n",pid);
wait(NULL);
printf("Child Complete\n");
exit(0);
}
Processes
Page 32
13. Explain how was the execution carried out in program in point 11? You may use a flow model to (3)
describe it.
Processes
Page 33
14. Using Exec: The fork system call creates a new process but that process contains, and is executing,
exactly the same code that the parent process has. More often than not, we'd like to run a new
program.
15. Example of Execve():The execve system call replaces the current process with a new program.Type
the following command in Terminal and show the output.
ls -aF /
Now execute the following code
/* execve: run a program */
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
Processes
Page 34
exit(1);
}
What is the outcome?
Processes
Page 35
17. Using fork() and exec(): The fork system call creates a new process. The execve system call
overwrites a process with a new program. A process forks itself and the child process execs a new
program, which overlays the one in the current process.
/* forkexec: create a new process. */
/* The child runs "ls -aF /". The parent wakes up after 5 seconds */
#include <stdlib.h>
/* needed to define exit() */
#include <unistd.h>
/* needed for fork() and getpid() */
#include <stdio.h>
/* needed for printf() */
Int main(int argc, char **argv) {
void runit(void);
int pid; /* process ID */
switch (pid = fork()) {
case 0:
/* a fork returns 0 to the child */
runit();
break;
default: /* a fork returns a pid to the parent */
sleep(5); /* sleep for 5 seconds */
Processes
Page 36
Processes
(3)
Page 37
NULL,
FALSE,
0,
Processes
// No creation flags.
Page 38
NULL,
NULL,
&si,
&pi )
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return -1;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
What is the Outcome?
Processes
Page 39
20. Which OS gives you a better interface for creating and executing child programs and why?
Processes
Page 40
(1)
Page 41
http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/exec.html
http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/forkexec.html
http://www.advancedlinuxprogramming.com/alp-folder/alp-ch03-processes.pdf
22. Summary: This experiment allows the students to work processes in Ubuntu using fork() command.
Code for process creation in windows is also given. The use of Exec() is also observed.
Processes
Page 42
1.
Objectives:
(a). Using Java Threads
(b). Thread Synchronization
2.
3.
Software Required:
(a). Java
(b). Windows/Ubuntu
4.
5.
Context Switch Using Threads: Switching among threads is much cheaper than to
switch processes as threads share the same process area.
6.
Java Threads; Every thread in Java is created and controlled by the java.lang.Thread
class. A Java program can have many threads, and these threads can run concurrently,
either asynchronously or synchronously. Following shows the methods in Object and
Thread Classes of Java.
7.
Thread Management
Page 43
}
One way to create a thread in java is to implement the Runnable Interface and then
instantiate an object of the class. We need to override the run() method into our class
which is the only method that needs to be implemented. The run() method contains the
logic of the thread.
(a). A class implements the Runnable interface, providing the run() method that will be
executed by the thread. An object of this class is a Runnable object.
(b). An object of Thread class is created by passing a Runnable object as argument to
the Thread constructor. The Thread object now has a Runnable object that
implements the run() method.
(c). The start() method is invoked on the Thread object created in the previous step.
The start() method returns immediately after a thread has been spawned.
(d). The thread ends when the run() method ends, either by normal completion or by
throwing an uncaught exception.
8.
Thread Creation by Extending the Thread Class: The procedure for creating threads
based on extending the Thread is as follows:
(a). A class extending the Thread class overrides the run() method from the Thread
class to define the code executed by the thread.
(b). This subclass may call a Thread constructor explicitly in its constructors to
initialize the thread, using the super() call.
(c). The start() method inherited from the Thread class is invoked on the object of the
class to make the thread eligible for running.
9.
Thread Management
Page 44
(1)
//Constuctor
//Call to constructor of Thread class
}
public void run(){
System.out.println("I
am
a
thread
"+Thread.currentThread().getName());
and
my
name
is
}
public static void main(String[] args) {
ThreadExample t = new ThreadExample("Thread 01"); //Create a thread
object
t.start();
OutCome:
Thread Management
Page 45
10.
Create another thread object and execute it. Show code and outcome here:
Thread Management
Page 46
(1)
11.
Execute the following code for producer and consumer. Execute and show outcome:
/**
* @(#)ProducerConsumerUsingThreads.java
* ProducerConsumerUsingThreads application
* @author Engr. Umar Mahmud
* @version 1.00 2013/12/20
*/
public class ProducerConsumerUsingThreads extends Thread {
//To create producer and consumer as threads
private int x = 0;
//Shared variable
private int maxLimit = 5;
//Maximum Limit to simulate a buffer
public ProducerConsumerUsingThreads(String threadName){
//Constuctor
super(threadName);
Thread Management
(1)
}
public void run(){
for(int i = 0; i< 10; i++){
System.out.println(Thread.currentThread().getName());
if(Thread.currentThread().getName().startsWith("Producer")){
//In a producer
if(x<maxLimit){
x++;
}
else{
System.out.println("\nProducer blocked");
yield();
//Give way to another thread
}
}
else
if(Thread.currentThread().getName().startsWith("Consumer")){
//In a Consumer
if(x>0){
x--;
Thread Management
Page 48
}
else{
System.out.println("\nConsumer blocked");
yield();
//Give way to another thread
}
}
else{
//default case
System.out.println("Some Error");
}
}
}
public static void main(String[] args) {
ProducerConsumerUsingThreads
p
ProducerConsumerUsingThreads("Producer");
new
ProducerConsumerUsingThreads
c
ProducerConsumerUsingThreads("Consumer");
new
p.start();
c.start();
Thread Management
Page 49
Re-execute the code and identify if the output trace is same as before.
Thread Management
Page 50
Again re-execute the code and identify if the output trace is same as before.
Thread Management
Page 51
12.
Thread Management
Page 52
(2)
13.
Create two threads one to read from a file and the other to write into another file. Show
the output and code for a given text file.
/* @(#)ThreadExample.java
* @author Engr. Umar Mahmud
* @version 1.00 2014/4/25
*/import java.io.*;
import java.util.Scanner;
public class exp512 extends Thread {
threads
public exp512(String threadName){
super(threadName);
Thread class
}
String path = "E:\\waqar.txt";
public void run(){
Thread Management
Page 53
//Constuctor
//Call to constructor of
(5)
if(Thread.currentThread().getName().equals("Read"))
readFromFile();
else if(Thread.currentThread().getName().equals("Write"))
writeToFile();
else
System.out.println("Apologies! Thread got confused");
}
public static void main(String[] args) throws IOException {
exp512 readThread = new exp512("Read");
exp512 writeThread = new exp512("Write");
//
Thread Management
Page 54
try {
fin = new FileInputStream(path);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
// read characters until EOF is encountered
do {
try {
i = fin.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread Management
Page 55
Page 56
} catch (IOException e) {
e.printStackTrace();
}
}
Thread Management
Page 57
OutPut:
14.
References
http://www.youtube.com/watch?v=KxTRsvgqoVQ
http://www.youtube.com/watch?v=D0u2USIonds
http://www.youtube.com/watch?v=CKFq-WTZZc8
http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html [MUST VISIT]
http://www.javabeginner.com/learn-java/java-threads-tutorial
15.
Summary: This experiment allows the students to work with threads and see how thread
switching works. Students work with examples to solve producer consumer as well as
reader writer problem using threads
Thread Management
Page 58
1.
Objectives:
(a). Using VM Ware
(b). Loading Ubuntu on VM Ware
(c). Working with system tools in Linux as well as Windows while using VM Ware
2.
3.
Software/Language Required:
(a). VM Ware
(b). Windows OS/Ubuntu 10
4.
VM Ware: VMware, Inc. is an American software company that provides cloud and
virtualization software and services and was the first to successfully virtualize the x86
architecture. VMware's desktop software runs on Microsoft Windows, Linux, and Mac OS
X, while its enterprise software hypervisors for servers, VMware ESX and VMware ESXi,
are bare-metal hypervisors that run directly on server hardware without requiring an
additional underlying operating system.
5.
6.
Installing VM Ware: Install VMWare (if not installed already on your machine). Install
Ubuntu on WM Ware.
7.
See the Task manager in windows and identify if the VM Ware is shown as a
service/process? Show its attributes here:
Virtual Machines
Page 59
(3)
Based on the attributes information, where does VM Ware reside? i.e., on Windows or on
hardware? Give reasons
8.
Open Terminal in Ubuntu as part of VM Ware. Type the commandifconfig. What is the
output? Show here
Virtual Machines
Page 60
(1)
9.
Open command prompt in Windows. Typeipconfig. What is the output? Show here.
Virtual Machines
Page 61
(1)
10.
Virtual Machines
Page 62
(3)
11.
Write a C++ program that creates an array of 200 integers, and iteratively squares each
element of that array. Execute the code and observe Task manager as well as system
monitor (in Ubuntu) simultaneously. Looking at the CPU load what is your observation?
Virtual Machines
Page 63
(2)
12.
References:
https://www.vmware.com/pdf/ws6_manual.pdf
https://www.vmware.com/support/ws55/doc/ws_newguest_setup_simple_steps.html
https://en.wikipedia.org/wiki/VMware
http://www.youtube.com/watch?v=z2aVFqp0oc8
https://en.wikipedia.org/wiki/Hypervisor
13.
Summary: This experiment allows the students to work with VM Ware and load a
different OS on it. The students are also able to observe different parameters both in Linux
as well Windows using VM Ware and draw appropriate conclusions.
Virtual Machines
Page 64
1. Objectives:
(a). Module programming
(b). Developing modules in Ubuntu
(c). Hello World module in Ubuntu
2. Time Required: 3 hrs
3. Software Required:
(a). gcc compiler
(b). C language
(c). Ubuntu
4. Modules: In computing, a loadable kernel module (or LKM) is an object file that contains
code to extend the running kernel, or so-called base kernel, of an operating system. LKMs are
typically used to add support for new hardware, file-systems, or for adding system calls.
When the functionality provided by an LKM is no longer required, it can be unloaded in
order to free memory and other resources.
Modules are programs that execute in the OS shell or Ring 0.
5. Creating Hello World Module: In this experiment the simplest hello world module will be
created. The steps are as follows: -
(
1
)
(a).
Make a folder on the desktop for this lab. Make sure that the name of the folder does
not have a space character in it. Write the name of the folder here saifisystem_____.
(b).
Create a text file using a text editor with the name hello-1.c. You may create any file
name but the extension should be .c.
(c).
Write the following code in the text file. Text file is edited using the Text Edit tool in
Linux
Module Programming I
Page 65
#include <linux/module.h>
/* Needed by all modules */
#include <linux/kernel.h>
/* Needed for KERN_INFO */
int init_module(void){
printk(KERN_INFO "Sky Fall\n");
// A non 0 return means init_module failed
// module can't be loaded.
return 0;
}
void cleanup_module(void){
printk(KERN_INFO "Breaking Dawn.\n");
}
(d).
(e).
Kernel modules must have at least two functions: a "start" (initialization) function
called init_module() which is called when the module is loaded (insmod) into the
kernel, and an "end" (cleanup) function called cleanup_module() which is called just
before it is removed (rmmod).
(f).
(g).
(h).
6. Compiling Hello World Module: Now the module will be compiled by creating a make file.
The steps are as under: -
(
3
)
(a). Create a new file using the text editor and store it with the name Makefile in the
working directory. Do not use any extensions while storing the file.
Module Programming I
Page 66
modules
clean:
(c). The first line should show the name of your file with .o extension after the +=
characters.
(d). Do not forget to put a tab character before make in both instances of the keyword
make.
(e). In the terminal type sudo make. If asked for the password type in the password.
(f). What is the outcome of this step (if correctly executed)? Show the output as well as
the names of the files created in the working directory.
Module Programming I
Page 67
(g). Use modinfo hello-1.ko to see what kind of information it is. Show the output here.
Module Programming I
Page 68
7. Loading Module: To load the module in kernel type sudo insmod ./hello-1.ko andremember
to rename hello-1 if you have different file name.
8. Type lsmod and see if the module is loaded. Show the screen capture here.
(
1
)
Module Programming I
Page 69
9. Viewing Log: To view log type dmesg. Show the output here.
(
1
)
Module Programming I
Page 70
Removing Modules: To remove module type sudo rmmod hello-1 andremember to rename
0. hello-1 if you have different file name.
1
1.
Module Programming I
Page 71
2.
(
1
)
Module Programming I
Page 72
1
3.
Hello World Improved: Write the following code in a new file. Name the file hello-2.c
#include <linux/module.h>
/* Needed by all modules */
#include <linux/kernel.h>
/* Needed for KERN_INFO */
#include <linux/init.h>
/* Needed for the macros */
static int __init hello_2_init(void){
printk(KERN_INFO "Hello, world 2\n");
return 0;
}
static void __exit hello_2_exit(void){
printk(KERN_INFO "Goodbye, world 2\n");
}
module_init(hello_2_init);
module_exit(hello_2_exit);
Module Programming I
Page 73
Remember that there are two underscores before init and exit keywords
1
4.
5.
1
6.
1
Insert modules by typing sudo insmod ./hello-1.ko and sudo insmod ./hello-2.ko
7. andremember to rename filenames if you have different file name
Module Programming I
Page 74
8.
(
1
)
Module Programming I
Page 75
Remove the modules by typing sudo rmmod hello-1 and then sudo rmmod hello-2
9.
2
0.
1
)
Module Programming I
Page 76
Init data: The __init macro causes the init function to be discarded and its memory freed
1. once the initfunction finishes for builtin drivers, but not loadable modules. If you think
about when the init function isinvoked, this makes perfect sense.There is also an __initdata
which works similarly to __init but for init variables rather than functions.
Type the following code and name it hello-3.c
Module Programming I
Page 77
(
1
)
Module Programming I
Page 78
2.
Module Programming I
Page 79
Module Programming I
Page 80
Resources:
3.
https://en.wikipedia.org/wiki/Loadable_kernel_module
www.tldp.org/LDP/lkmpg/2.6/lkmpg.pdf
http://www.tldp.org/LDP/lkmpg/2.6/html/index.html
2
Summary:
Module Programming I
Page 81
4. students are required to create simple hello world modules. The loading and removal is also
observed.
Module Programming I
Page 82
Objectives:
(a). Module Programming in Linux
(b). Licencing and command line arguments in modules
2.
3.
Software Required:
(a). Java/C/C++/C#
(b). Windows/Ubuntu
4.
License Information: In kernel 2.4 and later, a mechanism was devised to identify code
licensed under the GPL (and friends) so people can be warned that the code is non opensource. This is accomplished by the MODULE_LICENSE() macro which is demonstrated
in the next piece of code. By setting the license to GPL, you can keep the warning from
being printed.
5.
6.
Create
the following
module and name
as hello-4.c
* hello-4.c
- Demonstrates
module
documentation.
/*
*/
#include <linux/module.h>
/* Needed by all modules */
#include <linux/kernel.h>
/* Needed for KERN_INFO */
#include <linux/init.h>
/* Needed for the macros */
#define DRIVER_AUTHOR "Type your name and email here
#define DRIVER_DESC
"Give the description of your driver"
static int __init init_hello_4(void)
{
printk(KERN_INFO "Hello, world 4\n");
return 0;
}
static void __exit cleanup_hello_4(void)
{
printk(KERN_INFO "Goodbye, world 4\n");
}
module_init(init_hello_4);
module_exit(cleanup_hello_4);
MODULE_LICENSE("GPL");
MODULE_AUTHOR(DRIVER_AUTHOR); /* Who wrote this module? */
MODULE_DESCRIPTION(DRIVER_DESC); /* What does this module do */
MODULE_SUPPORTED_DEVICE("testdevice");
Module Programming II
Page 83
7.
Module Programming II
Page 84
Module Programming II
Page 85
8.
Passing Command Line Arguments to Modules: Modules can take command line
arguments, but not with the argc/argv you might be used to.To allow arguments to be
passed to your module, declare the variables that will take the values of the command line
arguments as global and then use the module_param() macro, (defined in
linux/moduleparam.h) to set the mechanism up. At runtime, insmod will fill the variables
with any command line arguments that are given, like ./insmod mymodule.ko
myvariable=5. The variable declarations and macros should be placed at the beginning of
the module for clarity. The example code should clear up my admittedly lousy explanation.
The module_param() macro takes 3 arguments: the name of the variable, its type and
permissions for the corresponding file in sysfs. Integer types can be signed as usual or
unsigned.
int myint = 3;
module_param(myint, int, 0);
9.
Module Programming II
Page 86
Module Programming II
Page 87
10.
Module Programming II
Page 88
Module Programming II
Page 89
11.
Module Programming II
Page 90
12.
References:
https://en.wikipedia.org/wiki/Loadable_kernel_module
www.tldp.org/LDP/lkmpg/2.6/lkmpg.pdf
http://www.tldp.org/LDP/lkmpg/2.6/html/index.html
13.
Summary: In this experiment the students improved the modules in the previous
experiment by providing licensing information and also command line arguments.
Module Programming II
Page 91
Objectives:
(a). Executing system commands using java code
(b). Reading registry entries
(c). Reading version information through registry
2.
3.
Software Required:
(a). Windows
(b). NetBeans 8/Eclipse Kepler
(c). Borland/Turbo C/Dev++/Visual Studio
4.
5.
Type and Execute the following command in DOScmd /c dir. Show the outcome here.
Page 92
(1
)
Page 93
6.
Page 94
(1
)
catch(IOException e1) {}
catch(InterruptedException e2) {}
System.out.println("Done");
}
}
What is the outcome? Show here. (Make sure that the working directory is same for both Points 5 and
6).
7.
Write DOS command and Java code to execute CHKDSK. Show outcome of both programs here.
Page 95
(2
)
Page 96
8.
9.
Windows Registry: Windows Registry is a hierarchical database that stores configuration settings
and options on Microsoft Windows operating systems. It contains settings for low-level operating
system components and for applications running on the platform that have opted to use the Registry.
The kernel, device drivers, services, user interface and third party applications can all make use of the
Registry. The Registry also provides a means to access counters for profiling system performance.
Getting the System Version Program Example: The following example uses the GetVersionEx()
function to display the version of the currently running operating system. Relying on version
information is not the best way to test for a feature. Instead, refer to the documentation for the
Page 97
(1
feature of interest. If you must require a particular operating system, be sure to use it as a minimum
supported version, rather than design the test for the one operating system. This way, your detection
code will continue to work on future versions of Windows.
Page 98
Page 99
Page 100
elseif(osver.wProductType ==
VER_NT_DOMAIN_CONTROLLER)
VER_NT_SERVER
||
osver.wProductType
{
if((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 2))
{
if(osver.wSuiteMask & VER_SUITE_DATACENTER)
printf("Datacenter Edition ");
elseif(osver.wSuiteMask & VER_SUITE_ENTERPRISE)
printf("Enterprise Edition ");
elseif(osver.wSuiteMask == VER_SUITE_BLADE)
printf("Web Edition ");
else
printf("Standard Edition ");
}
elseif((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 0))
{
if(osver.wSuiteMask & VER_SUITE_DATACENTER)
printf("Datacenter Server ");
elseif(osver.wSuiteMask & VER_SUITE_ENTERPRISE)
printf("Advanced Server ");
System Commands and Registry Information
Page 101
==
else
printf("Server ");
}
// Windows NT 4.0
else
{
if(osver.wSuiteMask & VER_SUITE_ENTERPRISE)
printf("Server 4.0, Enterprise Edition ");
else
printf("Server 4.0 ");
}
}
}
// Test for specific product on Windows NT 4.0 SP5 and earlier
else
{
HKEY hKey;
char szProductType[BUFSIZE];
DWORD dwBufLen=BUFSIZE;
LONG lRet;
System Commands and Registry Information
Page 102
lRet
=
RegOpenKeyEx(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
0,
KEY_QUERY_VALUE,
&hKey);
if(lRet != ERROR_SUCCESS)
return FALSE;
else
printf("RegOpenKeyEx() is OK.\n");
lRet
=
RegQueryValueEx(hKey,
(LPBYTE)szProductType, &dwBufLen);
"ProductType",
Page 103
NULL,
NULL,
}
// Display service pack (if any) and build number.
if(osver.dwMajorVersion == 4 && lstrcmpi(osver.szCSDVersion, "Service Pack 6") == 0)
{
HKEY hKey;
LONG lRet;
// Test for SP6 versus SP6a.
lRet
=
"SOFTWARE\\Microsoft\\Windows
RegOpenKeyEx(HKEY_LOCAL_MACHINE,
Page 104
RegCloseKey(hKey);
}
// Windows NT 3.51 and earlier or Windows 2000 and later
else
{
printf("%s (Build %d)\n", osver.szCSDVersion, osver.dwBuildNumber & 0xFFFF);
}
break;
// Test for the Windows 95 product family.
case VER_PLATFORM_WIN32_WINDOWS:
if(osver.dwMajorVersion == 4 && osver.dwMinorVersion == 0)
{
printf("Microsoft Windows 95 ");
if(osver.szCSDVersion[1] == 'C' || osver.szCSDVersion[1] == 'B')
printf("OSR2 ");
}
if(osver.dwMajorVersion == 4 && osver.dwMinorVersion == 10)
{
printf("Microsoft Windows 98 ");
if(osver.szCSDVersion[1] == 'A')
System Commands and Registry Information
Page 105
printf("SE ");
}
if((osver.dwMajorVersion == 4) && (osver.dwMinorVersion == 90))
{
printf("Microsoft Windows Millennium Edition\n");
}
break;
case VER_PLATFORM_WIN32s:
printf("Microsoft Win32s\n");
break;
}
return TRUE;
}
Page 106
10
.
Retrieving and Displaying Object, Instance, and Counter Names: The performance data contains
information for a variable number of object types, instances per object, and counters per object type.
Therefore, the number and size of blocks in the performance data varies. To ensure that your
application correctly receives the performance data, you must use the offsets included in the
performance structures to navigate through the data. Every offset is a count of bytes relative to the
structure containing it. The reason the system uses offsets instead of pointers is that pointers are not
valid across process boundaries. The addresses that the process that installs the counters would store
would not be valid for the process that reads the counters. The following example displays the index
and name of each object, along with the indexes and names of its counters. The object and counter
names are stored in the registry, by index. This example creates a function, GetNameStrings(), to
load the indexes and names of each object and counter from the registry into an array, so that they can
be easily accessed. GetNameStrings() uses the following standard registry functions to access the
data: RegOpenKey(), RegCloseKey(), RegQueryInfoKey(), and RegQueryValueEx().
This example creates the following functions for navigating the performance data: FirstObject,
FirstInstance, FirstCounter, NextCounter, NextInstance, and NextCounter. These functions navigate
the performance data by using the offsets stored in the performance structures.
Execute the following programs and show outcome.
// #define _WIN32_WINNT 0x0502 // Windows Server 2003 family
// For Win Xp, change accordingly...
#define _WIN32_WINNT 0x0501
Page 107
(1
)
20000
Page 108
{
return((PPERF_INSTANCE_DEFINITION)((PBYTE)PerfObj
>DefinitionLength));
PerfObj-
}
PPERF_INSTANCE_DEFINITION
PerfInst)
NextInstance(PPERF_INSTANCE_DEFINITION
{
PPERF_COUNTER_BLOCK PerfCntrBlk;
PerfCntrBlk = (PPERF_COUNTER_BLOCK)((PBYTE)PerfInst + PerfInst->ByteLength);
return((PPERF_INSTANCE_DEFINITION)((PBYTE)PerfCntrBlk + PerfCntrBlk>ByteLength));
}
PPERF_COUNTER_DEFINITION FirstCounter(PPERF_OBJECT_TYPE PerfObj)
{
return((PPERF_COUNTER_DEFINITION) ((PBYTE)PerfObj + PerfObj->HeaderLength));
}
PPERF_COUNTER_DEFINITION
PerfCntr)
NextCounter(PPERF_COUNTER_DEFINITION
{
return((PPERF_COUNTER_DEFINITION)((PBYTE)PerfCntr + PerfCntr->ByteLength));
}
// Load the counter and object names from the registry to the
System Commands and Registry Information
Page 109
HKEY hKeyPerflib009;
DWORD dwBufferSize;
// size of dwBuffer
LPSTR lpCurrentString;
DWORD dwCounter;
Page 110
dwBufferSize = sizeof(dwBuffer);
if(RegQueryValueEx(
hKeyPerflib,
"Last Counter",
NULL,
NULL,
(LPBYTE) &dwBuffer,
&dwBufferSize) != ERROR_SUCCESS)
return FALSE;
else
printf("RegQueryValueEx() is OK.\n");
RegCloseKey(hKeyPerflib);
// Allocate memory for the names array.
lpNamesArray = (LPTSTR *)malloc((dwBuffer+1) * sizeof(LPSTR));
if(lpNamesArray == NULL)
return FALSE;
// Open the key containing the counter and object names.
if(RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib\\009",
System Commands and Registry Information
Page 111
0,
KEY_READ,
&hKeyPerflib009) != ERROR_SUCCESS)
return FALSE;
else
printf("RegOpenKeyEx() is OK.\n");
// Get the size of the largest value in the key (Counter or Help).
if(RegQueryInfoKey(
hKeyPerflib009,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
&dwMaxValueLen,
NULL,
NULL) != ERROR_SUCCESS
System Commands and Registry Information
Page 112
)
return FALSE;
else
printf("RegQueryInfoKey() is OK.\n");
// Allocate memory for the counter and object names.
dwBuffer = dwMaxValueLen + 1;
lpNameStrings = (LPTSTR)malloc(dwBuffer * sizeof(CHAR));
if(lpNameStrings == NULL)
{
free(lpNamesArray);
return FALSE;
}
else
printf("Memory allocated for lpNameStrings.\n");
// Read the Counter value.
if(RegQueryValueEx(
hKeyPerflib009,
"Counter",
NULL,
NULL,
System Commands and Registry Information
Page 113
(LPBYTE)lpNameStrings,
&dwBuffer) != ERROR_SUCCESS)
return FALSE;
else
printf("RegQueryValueEx() is OK.\n");
printf("Please wait...\n");
// Load names into an array, by index.
for(lpCurrentString = lpNameStrings; *lpCurrentString;
lpCurrentString += (lstrlen(lpCurrentString)+1))
{
dwCounter = atol(lpCurrentString);
lpCurrentString += (lstrlen(lpCurrentString)+1);
lpNamesArray[dwCounter] = (LPSTR)lpCurrentString;
}
return TRUE;
}
// Display the indexes and/or names for all performance objects, instances, and counters.*
int main()
{
PPERF_DATA_BLOCK PerfData = NULL;
System Commands and Registry Information
Page 114
PPERF_OBJECT_TYPE PerfObj;
PPERF_INSTANCE_DEFINITION PerfInst;
PPERF_COUNTER_DEFINITION PerfCntr, CurCntr;
PPERF_COUNTER_BLOCK PtrToCntr;
DWORD BufferSize = TOTALBYTES;
DWORD i, j;
LONG k;
// Get the name strings through the registry.
if(!GetNameStrings())
return FALSE;
// Allocate the buffer for the performance data.
PerfData = (PPERF_DATA_BLOCK) malloc(BufferSize);
if(PerfData == NULL)
return FALSE;
while(RegQueryValueEx(
HKEY_PERFORMANCE_DATA,
"Global",
NULL,
NULL,
(LPBYTE) PerfData,
System Commands and Registry Information
Page 115
&BufferSize) == ERROR_MORE_DATA)
{
// Get a buffer that is big enough.
BufferSize += BYTEINCREMENT;
PerfData = (PPERF_DATA_BLOCK) realloc(PerfData, BufferSize);
}
// Get the first object type.
PerfObj = FirstObject(PerfData);
// Process all objects.
for(i=0; i < PerfData->NumObjectTypes; i++)
{
// Display the object by index and name.
printf("\nObject %ld: %s\n", PerfObj->ObjectNameTitleIndex, lpNamesArray[PerfObj>ObjectNameTitleIndex]);
// Get the first counter.
PerfCntr = FirstCounter(PerfObj);
if(PerfObj->NumInstances > 0)
{
// Get the first instance.
PerfInst = FirstInstance(PerfObj);
System Commands and Registry Information
Page 116
Page 117
{
// Get the counter block.
PtrToCntr = (PPERF_COUNTER_BLOCK)((PBYTE)PerfObj + PerfObj>DefinitionLength);
// Retrieve all counters.
for(j=0; j < PerfObj->NumCounters; j++)
{
// Display the counter by index and name.
printf("\tCounter %ld: %s\n", PerfCntr->CounterNameTitleIndex,
lpNamesArray[PerfCntr->CounterNameTitleIndex]);
// Get the next counter.
PerfCntr = NextCounter(PerfCntr);
}
}
// Get the next object type.
PerfObj = NextObject(PerfObj);
}
// Release all the memory back to system...
free(lpNamesArray);
free(lpNameStrings);
System Commands and Registry Information
Page 118
free(PerfData);
return TRUE;
}
Page 119
11
.
Page 120
(4
)
Page 121
12
.
References:
http://www.java-samples.com/showtutorial.php?tutorialid=8
https://en.wikipedia.org/wiki/Command_%28computing%29
http://ss64.com/nt/
https://en.wikipedia.org/wiki/List_of_DOS_commands
https://en.wikipedia.org/wiki/Windows_Registry
http://www.tenouk.com/ModuleP.html
http://www.tenouk.com/ModuleP1.html
13
.
Summary: This experiments provides codes to execute system commands as well as to explore
registry entries available in Windows.
Page 122
Page 123
EXPERIMENT 10 SOCKETS
1.
Objectives:
(a). Sockets
(b). Communication using sockets
2.
3.
Software Required:
(a). Java
(b). Windows
(c). NetBeans 8/Eclipse Kepler
4.
Sockets
Page 124
5.
Socket and ServerSocket: Socket and ServerSocket classes are used to implement
socket programming. ServerSocket has constructors that create new ServerSocket
objects, methods that listen for connections on a specified port, and methods that return a
Socket object when a connection is made so that you can send and receive data. A new
ServerSocket is created on a particular port using a ServerSocket( ) constructor. In
following activity student will be able to find out open port on Local machine.
Page 125
}
}
6.
Sockets
Page 126
while (true){
Socket client = server.accept();
BufferedReader
r
=
new
BufferedReader(new
InputStreamReader (client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(),
true);
w.println("Welcome to the Java EchoServer. Type 'bye' to
close.");
String line;
do{
line = r.readLine(); //read from Cleint
if ( line != null )
w.println("Got: "+ line);
}
while ( !line.trim().equals("bye") );
client.close();
}
}
catch (Exception err){
System.err.println(err);
}
Sockets
Page 127
}
public static void main(String[] args){
EchoServer s = new EchoServer(9999);
s.serve();
}
private ServerSocket server;
}
//(EchoClient.java)
import java.io.*;
import java.net.*;
public class EchoClient{
public static void main(String[] args){
try{
Socket s = new Socket("127.0.0.1", 9999);
BufferedReader r = new BufferedReader(new InputStreamReader
(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
Sockets
Page 128
BufferedReader
InputStreamReader(System.in));
con
new
BufferedReader(new
String line;
do{
line = r.readLine(); //Read from Server
if ( line != null )
System.out.println(line); //print if not null
line = con.readLine(); //Read from user
w.println(line);
//send to server
}while ( !line.trim().equals("bye") );
}
catch (Exception err){
System.err.println(err);
}
}
}
7.
Sockets
Page 129
(2)
8.
Write a code that reads a file from the client and sends to the server. The server then
writes the file at the server end. Show code and output here.
9.
Resources:
http://www.oracle.com/technetwork/java/socket-140484.html
Sockets
Page 130
(8)
http://www.tutorialspoint.com/java/java_networking.htm
14.
Summary: This experiment provides example to create Server Socket and Client
Sockets using Java. The students are then asked to send a file through this connection.
Sockets
Page 131
Sockets
Page 132