0% found this document useful (0 votes)
43 views

NP Lab Theory:: 1) To Create Thread by Inheriting Thread Class

1. Java provides built-in support for multithreaded programming through the Thread class. A thread represents a separate path of execution within a program. Threads exist in several states including new, runnable, blocked, suspended, and terminated. 2. There are two main ways to create threads in Java - by extending the Thread class and overriding the run() method, or by implementing the Runnable interface and passing a Runnable object to the Thread constructor. 3. Common thread methods include getName(), setName(), getPriority(), setPriority(), isAlive(), sleep(), which respectively get/set the name, get/set the priority, check if alive, and pause execution for a period.

Uploaded by

poornima
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

NP Lab Theory:: 1) To Create Thread by Inheriting Thread Class

1. Java provides built-in support for multithreaded programming through the Thread class. A thread represents a separate path of execution within a program. Threads exist in several states including new, runnable, blocked, suspended, and terminated. 2. There are two main ways to create threads in Java - by extending the Thread class and overriding the run() method, or by implementing the Runnable interface and passing a Runnable object to the Thread constructor. 3. Common thread methods include getName(), setName(), getPriority(), setPriority(), isAlive(), sleep(), which respectively get/set the name, get/set the priority, check if alive, and pause execution for a period.

Uploaded by

poornima
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

NP Lab Theory:

1) To create Thread by inheriting Thread class:

MULTI-THREADING:
A thread is actually a lightweight process. Unlike many other computer languages, Java
provides built-in support for multithreaded programming. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is called
thread and each thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.Threads reduce inefficiency by preventing the waste of CPU
cycles.
Threads exist in several states. Following are those states:
● New – When we create an instance of Thread class, a thread is in a new state.
● Runnable – The Java thread is in running state.
● Suspended – A running thread can be suspended, which temporarily suspends its
activity. A suspended thread can then be resumed, allowing it to pick up where it left
off.
● Blocked – A java thread can be blocked when waiting for a resource.
● Terminated – A thread can be terminated, which halts its execution immediately at
any given time. Once a thread is terminated, it cannot be resumed.

CREATING THREADS:

Java’s multithreading system is built upon the Thread class, its methods, and its companion
interface, Runnable. To create a new thread, your program will either extend Thread or
implement the Runnable interface.

● By implementing the Runnable interface.


 By extending the Thread

EXTENDING JAVA THREAD:

The second way to create a thread is to create a new class that extends Thread, then
override the run() method and then to create an instance of that class. The run()
method is what is executed by the thread after you call start().
2) To create Thread by implementing Runnable interface:
RUNNABLE INTERFACE:

The easiest way to create a thread is to create a class that implements the Runnable

interface. To implement Runnable interface, a class need only implement a single

method called run ().


3)To implement methods like getName, setName, getPriority ,setPriority

,isAlive ,sleep:

Java Thread setPriority() method

The setPriority() method of thread class is used to change the thread's priority. Every thread has a
priority which is represented by the integer number between 1 to 10.

Thread class provides 3 constant properties:

public static int MIN_PRIORITY: It is the maximum priority of a thread. The value of it is 1.

public static int NORM_PRIORITY: It is the normal priority of a thread. The value of it is 5.

public static int MAX_PRIORITY: It is the minimum priority of a thread. The value of it is 10.

We can also set the priority of thread between 1 to 10. This priority is known as custom priority or
user defined priority.

Syntax

1. public final void setPriority(int a)

Parameter

a: It is the priority to set this thread to.

Return

It does not return any value.

Exception

IllegalArgumentException: This exception throws if the priority is not in the range MIN_PRIORITY to
MAX_PRIORITY.
SecurityException: This exception throws if the current thread cannot modify this thread.

Java Thread getPriority() method

The getPriority() method of thread class is used to check the priority of the thread. When we create
a thread, it has some priority assigned to it. Priority of thread can either be assigned by the JVM or
by the programmer explicitly while creating the thread.

The thread's priority is in the range of 1 to 10. The default priority of a thread is 5.

Syntax

1. public final int getPriority()

Return

It returns the thread's priority.

Java Method getName() Method

The getName() method of Method class returns the name of the method represented by this
Method object, as a String.

Syntax

1. public String getName()

Parameter

No parameter is passed.
Returns

the simple name of the underlying member

Throws

Does not throw the exception.

Java Thread setName() method

The setName() method of thread class is used to change the name of the thread.

Syntax

1. public final void setName(String a)

Parameter

1. a = It shows the new name for the thread.

Return

1. This method does not return any value.

Exception

SecurityException: This exception throws if the current thread cannot modify the thread.

Java Thread isAlive() method


The isAlive() method of thread class tests if the thread is alive. A thread is considered alive when the
start() method of thread class has been called and the thread is not yet dead. This method returns
true if the thread is still running and not finished.

Syntax

1. public final boolean isAlive()

Return

This method will return true if the thread is alive otherwise returns false.

Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

public static void sleep(long miliseconds)throws InterruptedException

public static void sleep(long miliseconds, int nanos)throws InterruptedException


.

4)To copy the content of one file to another using byte oriented i/o:

The Java Input/output (I/O) is a part of java.io package. The java.io package contains a relatively

large number of classes that support input and output operations

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are

descended from InputStream and OutputStream. There are many byte stream classes. To

demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and

FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in

the way they are constructed.

5)To copy the contents of one file to another using character oriented i/o:

FileReader: We can use this class to read a character data from the file.

Constructors:

FileReader fr = new FileReader (String fname);

FileReader fr = new FileReader(File f);

Methods:
int read(): It attempts to read next character from the file and returns its Unicode value. If the next
value is not available then this method returns ‘-1’. As this returns Unicode value, at the time of
printing we have to perform typecasting.

int read(char[] ch):It attempts to read enough characters from the file into character array and
returns number of characters copied from the file. Object.

Void close():It is used to close the FileReader.

PrintWriter: It is the most enhanced writer to write charcter data to the file. The main advantage
of printWriter over BufferedWriter and FileWriter is we can write any type of primitive data directly
to the file. PrintWriter can communicate directly with the file and can communicate via writer object
also.

Constructors:

PrintWriter pw = new PrintWriter(String fname);

PrintWriter pw = new PrintWriter(File f);

PrintWriter pw = new PrintWriter(writer w);

Methods:

void print(String s) : This method prints a string.

void print(float f):This method prints a floating-point number.

void print(int i):This method prints an integer.

void print(char ch):This method prints an character.


All character stream classes are descended from Reader and Writer. As with byte streams, there are

character stream classes that specialize in file I/O: FileReader and FileWriter. Character Streams that

Use Byte Streams Character streams are often "wrappers" for byte streams. The character stream

uses the byte stream to perform the physical I/O, while the character stream handles translation

between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses

FileOutputStream. There are two general-purpose byte-to-character "bridge" streams:

InputStreamReader and OutputStreamWriter. Use them to create character streams when there are

no prepackaged character stream classes that meet your needs.

6) To copy the contents of one file to another using line oriented i/o:

BufferedReader: We can use  BufferedReader class to read character data from the file .The
main advantage of  BufferedReader when compared to FileReader is we can read the data line by
line in addition to character by character.  BufferedReader cannot communicate directly with the
file and it can communicate via some Reader object.

Constructors:

BufferedReader br=new  BufferedReader (Reader r);

BufferedReader br=new  BufferedReader (Reader r, int buff_size);

Methods:

String readLine(): It attempts to read next line from the file and returns it. If the next line not
available then this method returns null.

PrintWriter: It is the most enhanced writer to write charcter data to the file. The main advantage
of printWriter over BufferedWriter and FileWriter is we can write any type of primitive data directly
to the file. PrintWriter can communicate directly with the file and can communicate via writer object
also.
Constructors:

PrintWriter pw = new PrintWriter(String fname);

PrintWriter pw = new PrintWriter(File f);

PrintWriter pw = new PrintWriter(writer w);

Methods:

void Println(int a): This method prints the integer and then terminates the line.

void Println(char ch): It is used to prints the character and then terminates the line.

void println(char[] x):This method prints an array of characters and then terminates the line.

void Println(String s This method prints the string and then terminates the line

Line-Oriented I/O

Character I/O usually occurs in bigger units than single characters. One common unit is the line: a

string of characters with a line terminator at the end. A line terminator can be a carriagereturn/line-

feed sequence ("\r\n"), a single carriage-return ("\r"), or a single line-feed ("\n"). Supporting all

possible line terminators allows programs to read text files created on any of the widely used

operating systems.

7) To read a string, int, float and double from keyboard using scanner
class:
This class accepts a File, InputStream, Path and, String objects, reads all the primitive data
types and Strings (from the given source) token by token using regular expressions. By
default, whitespace is considered as the delimiter (to break the data into tokens).
To read data from keyboard you need to use standard input as source (System.in). For each
datatype a nextXXX() is provided namely, nextInt(), nextShort(), nextFloat(), nextLong(),
nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(),
nextFloat(), next().
8)to identify the active ports on local system
Active ports:
A port is an integer value ranging from 1 to 65535. It is used to uniquely identify an
application in a system, i.e. no two applications can run at the same port. Port numbers from
1 to 1023 are reserved for well-known protocols like HTTP, SMTP, FTP, TELNET, POP etc.
Ports used by some well-known protocols are given table 1.1. Ideally the port number is user
configurable. Alternatively, if a port number of 0 is specified, the operating system will select
an arbitrary valid and free port every time that the application is run. There are 65535 ports
per transport layer protocol i.e. we can have a UDP application and a TCP application
running at the same port. But two TCP applications or two UDP applications cannot run at
the same port.
Application Protocol port Transport protocol purpose
Echo 7 Tcp/udp Echo is a test protocol
used to verify that two
machines are able to
connect by having one
echo back the other’s
input
FTP 21 Tcp This port is used to
send ftp commands
like put and get
Telnet 23 Tcp Telnet is a protocol
used for intertractive
remote command line
sessions
SMTP 25 Tcp The simple mail
transfer protocol is
used to send a mail
HTTP 80 Tcp Hypertext transfer
protocol is the
underlying protocol of
the world wide web
POP 110 Tcp Post office protocol is
a protocol for the
transfer of
accumulated email
from the host to
sporadically connected
clients
NNTP 119 Tcp Usenet news transfer
is more formally
known as the network
news transfer
protocolnn

9)to identify the active ports in remote system


10)to implement the one-to-one chat using threads
Socket
A Socket represents a TCP connection between two applications across a TCP/IP network. It
is specified by IP Address and port number at both ends of the connection, although typically
only the server’s port number is encountered by the programmer. At the server a process
listens on a particular port. Every time a connection is made to the port, a TCP stream is
created between a server and the client.
ServerSocket
The ServerSocket class is a mechanism by which a server can accept connections from
clients over a network. The basic procedure for implementing a server is to open a
ServerSocket on a particular local port number, and then to wait for connections. Clients will
connect to this port and a connection will be established.
The ServerSocket class creates a Socket for each client connection and the server then can
handle these connections by creating an InputStream and an OutputStream and
communicating with the client through these streams.
A server must explicitly accept a connection from a ServerSocket by calling its accept()
method to obtain a Socket connection to a client. However, the operating system will actually
start accepting connections from clients as soon as the ServerSocket is created. These
connections will be placed in a queue and removed one by one as the server calls the accept()
method.
ServerSocket constructor allows a server to specify how many connections it wishes the
operating system to queue.
Constructors
ServerSocket (int port) throws IOException
ServerSocket(int port,int backlog) throws IOException

11) To implement Many-Many Chat (Broad Casting): Each Client opens a


socket connection to the chat server and writes to the socket. Whatever is
written by one system can be seen by all other systems.
 The purpose of a broadcast messenger is to create a server that is responsible for receiving
and responding to messages that are received from the clients to all the clients available on
the network. This is called as Broadcasting (to send the packet or message to all the hosts).
The server/client architecture is basically applied here because one of the computers will
act as a Server responding to client messages, while all other computers will behave
as Clients that only send requests to the server to perform some task. Sockets are logical
connections that are created to connect the computers to each other. A port number and a host
IP address/host name is required to create a socket
12)SFTP:
Simple file transfer protocol (SFTP) is an unsecured, lightweight version of File Transfer
Protocol (FTP), which runs on Transmission Control Protocol port number 115. It has some
useful features not present in Trivial FTP (TFTP), but is not as powerful as FTP.
SFTP can be implemented by opening a TCP connection to the remote host’s port 115. The
SFTP supports features such as user access control, file transfers, directory listing, directory
changing, file renaming and deleting. The SFTP does not receive as much attention as TFTP
and is not as accepted widely on the Internet.
SFTP supports user authentication where a user has to enter username and password to login
into the server. It also features hierarchical folders and file management.

13)develop a program to display the attributes and contents of the web


The Java URLConnection class represents a communication link between the URL and the
application. This class can be used to read and write data to the specified resource referred by
the URL.

How to get the object of URLConnection class:


The openConnection() method of URL class returns the object of URLConnection class.
Syntax: public URLConnection openConnection() throws  IOException{}

Displaying source code of a webpage by URLConnecton class:


The URLConnection class provides many methods, we can display all the data of a webpage
by using the getInputStream() method. The getInputStream() method returns all the data of
the specified URL in the stream that can be read and displayed.

14)to split the given url


URL SPLIT:
Java.net.URL class is an abstraction of a Uniform Resource Locator
Constructors
There are six constructors. All these constructors throw a MalformedURLException if we try
to create a URL for an unsupported protocol.
Constructing a URL from a string
1.public URL(String url) throws MalformedURLException
Constructing a URL from its component parts
2.public URL(String protocol, String hostname, String file) throws MalfomedURLException
This constructor sets the port to -1 so the default port for the protocol will be used.
Constructing a URL by specifying a port also
3.public URL(String protocol, String host, int port, String file) throws
MalformedURLException
If default port is not used by any server for a protocol,we use this constructor.
Constructing relative URLs
4.public URL(URL base,String relative) throws MalformedURLException
When we are parsing an HTML document at http://metalab.unc.edu/javafaq/index.html and
encounter a link to a file called mailinglist.html with no further qualifying information. In this
case
we use the URL to the document that contains the link to provide the missing information.
Constructors for specifying URL Stream Handlers:
public URL(URL base, String relative, URLStreamHandler handler) throws
MalformedURLException
public URL(String protocol, String host, int port, String file, URLStreamHandler) throws
MalformedURLException
Splitting a URL into pieces

public String getProtocol()


It returns a String containing the scheme of the URL.
public String getHost()
It returns a String containing the hostname of the URL.
public int getPort()
It returns the port number specified in the URL as an int.
public String getFile()
It returns a String that contains the path and file portion of a URL.
public String getPath()
It is a synonym for getFile().
public String getRef()
It returns the named anchor part of the URL.
public String getQuery()
It returns the query String of the URL.
public String getUserInfo()
Some URLs have usernames and occasionally password information.

15) To develop a program to simulate Telnet Client which allows to connect


to well-known servers and send and receive information.
TELNET:
Telnet Connections and Client/Server Operation:
Usually, the Telnet client is a piece of software that acts as an interface to the user,
processing keystrokes and user commands and presenting output from the remote
machine. The Telnet server is a program running on a remote computer that has been set
up to allow remote sessions
TCP Sessions and Client/Server Communication
Telnet runs over the connection-oriented Transmission Control Protocol (TCP).Telnet servers
listen for connections on well-known TCP port number 23. When a client wants to access a
particular server, it initiates a TCP connection to the appropriate server, which responds to
set up a TCP connection using the standard TCP three-way handshake.The TCP connection is
maintained for the duration of the Telnet session, which can remain alive for hours, days, or
even weeks at a time. The quality of service features of TCP guarantee that data is received
reliably and in order, and ensures that data is not sent at too high a rate for either client or
server.
Use of Telnet to Access Other Servers
The Telnet NVT representation is used by a variety of other protocols such as SMTP and
HTTP.This means that the same Telnet client that allows you to access a Telnet server can be
usedto directly access other application servers.
A Telnet connection is made to port 23 of the Telnet server stated through the IP address.
TELNET <address> <Port No.>

16) SMTP Client: Gives the server name, send an email to the recipient
using SMTP Commands
Simple Mail Transport Protocol (SMTP) is the protocol (mechanism) used to get email from
the sending computer all the way to the recipient's email server (SMTP server). This could be
at a company, an ISP, or a web mail hosting service (like Hotmail, Gmail, etc.). SMTP
servers run at port 25.
The sent message is stored on the SMTP server until it is retrieved. The message is then
removed from the server and stored on the local hard drive by POP3. So, it is important to
note 55 (that all successfully retrieved mail needs to be backed up at the local level, if
deemed necessary).

17) POP Client: Gives the server name, username and password, retrieve
the mails and allow manipulation of mailbox using POP commands.
Post Office Protocol Version 3(POP3) is the protocol used to download the email message
from a mail server to a computer using an email client program (like Outlook). When you
check your email, the messages are transferred to your computer and deleted from the server.
Web mail doesn't use POP3, because the messages stay on the server. You are viewing them
remotely. POP server runs at port 110.
The sent message is stored on the SMTP server until it is retrieved. The message is then
removed from the server and stored on the local hard drive by POP3. So, it is important to
note 55 (that all successfully retrieved mail needs to be backed up at the local level, if
deemed necessary).

18) Develop a program to implement UDP Echo Server and UDP Echo
Client.
UDP:
Java’s implementation of UDP is split into two classes: datagram packet and datagram
socket. The datagram packet class stuff byte of data into UDP packets called datagram and
let you unstuffed data grams that we receive. A datagram socket sends as well as receives
UDP datagrams.UDP does not have any notation of server socket. We use the same kind of
socket to send data and receive data.
DatagramPacket Class
Public final class DatagramPacket extends object
Constructors for receiving datagram
1. Public DatagramPacket(byte[] buffer, int length)
When a socket receives a datagram, it stores the datagram’s data part in buffer beginning at
buffer[0] and containing until the packet is completely stored or until ‘length’ bytes have
been written into the buffer.
Public DatagramPacket(byte[] buffer, int offset, int length)
This stores the data beginning at byte[offset] ‘length’ must be lessthan or equal to
buffer.Length-offset or else IllegalArgumentException will be thrown.
Constructors for sending datagram
public DatagramPacket(byte[] data, int length, InetAddress destination, int port)
public DatagramPacket(byte[] data, int offset, int length, InetAddress destination, int port)
Each constructor creates a new datagram packet to be sent to another host.
Get Methods
public InetAddress getAddress()
It returns an InetAddress object containing the address of the remote host.
Public int getPort()
It returns an integer specifying the remote port.
Public byte[] getData()
It returns a byte array containing the data from the datagram.
Public int getLength()
It returns the number of bytes of data in the datagram it may not be same as the length of
the
array returned by the getData()
Public int getOffset()
It returns the point in the array returned by getData() where the datagram begins.
Set Methods
public void setData(byte[] data)
public void setData(byte[] data, int offset, int length)
public void setAddress(InetAddress remote)
public void setPort(int port)
public void setLength(int length)
DatagramSocket class
All datagram sockets are bound to a local port, on which they listen for incoming data and
which they place in the header of outgoing datagram.
Constructors
Public DatagramSocket() throws SocketException
It creates a socket bound to an anonymous port.
Public DatagramSocket(int port) throws SocketException
It creates a socket that listens for incoming datagram’s on a specified port.
Public DatagramSocket(int port, InetAddress address) throws SocketException
This constructor is used on multi homed hosts.
Public void send(DatagramPacket dp) throws IOException)
This method is used to send datagram packet using datagram socket.
Public void receive(DatagramPacket dp) throws IOException)
It receives a single UDP datagram from a network and stores it in the preexisting datagram
packet object dp.
Public void close()
It frees the port occupied this socket.
Public int getLocalPort()
It returns the local port on which the socket is listening.

19) Develop a program to implement IP Multicasting.

Ip multicasting:
A multicast address is the address of a group of hosts called a multicast group. Multicast
addresses are IP addresses in the range 224.0.0.0 to 239.255.255.255(Class D addresses).
Any data sent to the multicast address is relayed to all the members of the group.
MulticastSocket Class:
public class MulticastSocket extends DatagramSocket
Constructors:
1.public MulticastSocket() throws SocketException
It creates a socket that is bound to an anonymous port (an unused port). It throws a
SocketException if the socket cannot be created.

2.Public MultiSocket(int port) throws SocketException


It creates a socket that receives datagram on a well-known port. On a Unix system a
program needs to be run with root privileges to create a MulticastSocket on a port
numbered from 1 to 1023.
Methods
1. public void joinGroup(InetAddress address) throws IOException
If the address that you try to join is not a multicast address it throws IOException. A single
MulticastSocket can join multiple multicast groups.
2. public void leaveGroup(inetAddress add) throws IOException
It signals that you no longer want to receive datagrams from the specified multicast group.
3. public void send(DatagramPacket packet, byte ttl) throws IOException
Sending data with a MulticastSocket is similar to sending data with a DatagramSocket.
4. public void setInterface(InetAddress address) throws SocketException
On a multi homed host, this method chooses the network interface used for multicast
sending and receiving.
5. public InetAddress getInterface() throws SocketException
It is not clear why this method would throw an exception; in any case you must be prepared
for it.
6. public void setTimeToLive(int ttl) throws IOException
This method sets the default TTL value used for packets sent from the socket using the
send(DatagramPacket dp) method inherited from DatagramSocket (as opposed to the
send(DatagramPacket dp,byte ttl) method in MulticastSocket).
7. public int getTimeToLive() throws IOException
This method returns the default TTL value of the MulticastSocket. It can handle full range
from 1 to 255 without truncation because it returns an int instead of a byte.

You might also like