Network Programming lab(java) - PowerPoint PPT Presentation

1 / 152
About This Presentation
Title:

Network Programming lab(java)

Description:

This PPT is Dedicated to my inner controller AMMA BHAGAVAN ONENESS Founders. Developed by, EDITED BY, S.V.G.REDDY, M.Siva Naga Prasad Associate professor, student ... – PowerPoint PPT presentation

Number of Views:105
Avg rating:3.0/5.0
Slides: 153
Provided by: git50
Category:

less

Transcript and Presenter's Notes

Title: Network Programming lab(java)


1
Network Programming lab(java)
  • This PPT is Dedicated to my inner controller
  • AMMA BHAGAVAN ONENESS Founders.
  • Developed by, EDITED BY,
  • S.V.G.REDDY, M.Siva Naga Prasad
  • Associate professor, student of M.tech(SE).
  • Dept.of CSE, GIT,
  • GITAM UNIVERSITY.

2
WELL KNOWN PORTS
3
Program
import java.io. import java.net. class
wkports public static void main(String
args) for(int i100ilt200i)
try Socket snew
Socket(host,i) System.out.println("There
is a server on port " i " of " host)
catch(UnknownHostException e)
System.err.println(e)
catch(IOException ie)
System.out.println(ie.getMessage())

4
Output-
5
One to One Chat Application
6
  • One-to-one communication is the act of an
    individual communicating with another.
  • In Internet terms, this can be done by e-mail
    but the most typical one-to-one communication in
    the Internet is instant
  • messaging as it does not consider many-to-many
    communication such as a chat room as an
    essential part of its scope

7
Description
  • The program displays what is written by one
    party to another by opening a socket connection
  • The Application contains two classes
  • 1.Chat client
  • 2.Chat server
  • The chat server class creates class creates a
    serves socket object which listens on port
    9999.The server socket accepts client socket and
    reads whatever is written by client and sends the
    message to the client thus allowing One-one
    communication
  • The Chat client class creates a socket
    object using which it sends message to the server
    on port 9999.The communication ends when the
    client send server says bye.

8
Topics Included in This.
  • Socket Programming
  • Exception Handling
  • I/O and StreamClasses

9
Socket Programming
  • A socket is one end-point of a two-way
    communication link between two programs running
    on the network. Socket classes are used to
    represent the connection between a client program
    and a server program. The java.net package
    provides two classes--Socket and Server
    Socket--that implement the client side of the
    connection and the server side of the connection,
    respectively.

10
Exception Handling
  • What is Exception???
  • An exception is an event that occurs during the
    execution of a program that disrupts the normal
    flow of instructions.
  • Why Exception Handling??
  • To terminate the program neatly in error
    condition or unexpected scenario.
  • To fix the problem at run time
  • To give user friendly messages to end user in
    case of unusual scenario or error

11
Exception Handling Using Java
  • When an error occurs within a method, the method
    creates an object and hands it off to the runtime
    system. The object, called an exception object,
    contains information about the error, including
    its type and the state of the program when the
    error occurred. Creating an exception object and
    handing it to the runtime system is called
    throwing an exception.
  • In java Exception handling is achieved by using
  • Try , Catch and Finally Blocks of code.
  • The Super class for all types of exceptions in
    java is java.lang.Exception

12
Try Block
  • try
  • code
  • CATCH BLOCK
  • catch (Exception ex)
  • ltdo something with exgt
  • catch
  • A method can catch an exception by providing an
    exception handler for that type of exception.

13
Client side program
import java.io. import java.net. import
java.lang. public class chatclient1 public
static void main(String args) throws
IOException Socket csocnull String
host if(args.lengthgt0) hostargs0 else host"l
ocalhost" PrintWriter poutnull BufferedReader
binnull try csocnew Socket(host,7) poutnew
PrintWriter(csoc.getOutputStream(),true) binnew
BufferedReader(new InputStreamReader(csoc.getInpu
tStream()))
14
catch(UnknownHostException e) System.err.printl
n("Unknownhost") System.exit(1) catch(IOExcept
ion e) BufferedReader innew
BufferedReader(new InputStreamReader(System.in))
String input while(true) inputin.readLine() p
out.println(input) String msgbin.readLine() Sys
tem.out.println("client "msg) if(msg.equals("by
e")) break in.close() pout.close() bin.close(
) csoc.close()
15
Server side program
import java.io. import java.net. import
java.lang. public class chatserver1 public
static void main(String args) throws
IOException ServerSocket ssocnull try ssocn
ew ServerSocket(7) catch(IOException
e) System.err.println("No connection
established") System.exit(1) Socket
csocnull try csocssoc.accept()
16
catch(IOException e) System.err.println("Not
accepted") System.exit(1) PrintWriter pwnew
PrintWriter(csoc.getOutputStream(),true) Buffered
Reader brnew BufferedReader(new
InputStreamReader(csoc.getInputStream())) String
inline String outline try DataInputStream
dinnew DataInputStream(System.in) while(true)
inlinebr.readLine() System.out.println("Server
"inline) outlinedin.readLine() pw.println(out
line) if(outline.equals("bye")) break
17
catch(Exception e) System.err.println(e) pw.c
lose() br.close() csoc.close() ssoc.close()

18
Server side output window
Clint side output window
19
Many to Many Chat Application
20
Description
  • Each client opens a socket connection to the chat
    server and writes to the socket whatever is
    written by one party can be seen by all other
    parties.
  • Chat Rooms in yahoo is the best example for this
    many to many chat application.

21
Connections Between Systems
22
Concepts Behind This
  • Socket communication
  • Exception Handling
  • IO
  • Multi Threading

23
Socket Programming
  • A socket is one end-point of a two-way
    communication link between two programs running
    on the network. Socket classes are used to
    represent the connection between a client program
    and a server program. The java.net package
    provides two classes--Socket and Server
    Socket--that implement the client side of the
    connection and the server side of the connection,
    respectively.

24
Classes in this program
  • It Reads text from a character-input stream,
    buffering characters so as to provide for the
    efficient reading of characters, arrays, and
    lines
  • It belongs to java.io Package.
  • BufferedReader (Reader in)           Create a
    buffering character-input stream that uses a
    default-sized input buffer.
  • Methods In This Class
  • ReadLine() Read a line of text. A line is
    considered to be terminated by
    any one of a line feed ('\n'), a carriage return
    ('\r'), or a carriage return followed immediately
    by a linefeed
  •  

25
  • Print Writer
  • Print formatted representations of objects to a
    text-output stream.
  • public PrintWriter(OutputStream out,boolean autoF
    lush)
  • Create a new PrintWriter from an existing
    OutputStream. This convenience constructor
    creates the necessary intermediate
    OutputStreamWriter, which will convert characters
    into bytes using the default character encoding.

26
Get Input/output Stream
  • InputStream
  • Returns an input stream for socket.
  • This method is Belongs socket class.
  • Socket class is belongs to java.net. Package
  • OutPutStream
  • Returns an output stream for socket.

27
Input Stream Reader
  • An InputStreamReader is a bridge from byte
    streams to character streams It reads bytes and
    decodes them into characters using a specified
    charset. The charset that it uses may be
    specified by name or may be given explicitly, or
    the platform's default charset may be accepted.
  • Public InputStreamReader(InputStream in)
  • Create an InputStreamReader that uses the
    default charset.

28
DataInputStream
  • A data input stream lets an application read
    primitive Java data types from an underlying
    input stream in a machine-independent way. An
    application uses a data output stream to write
    data that can later be read by a data input
    stream.
  • public DataInputStream(InputStream in)
  • Creates a DataInputStream that uses the
    specified underlying InputStream

29
Multi Threading
  • Thread is a Active part of execution.
  • Thread is a path of execution.
  • Threads are also called as lightweight process
  • Threads are executed in parallel.

30
Multithreading using java
  • We can implement multi threading using java in 2
    ways
  • 1.)By inheriting Thread class
  • or
  • 2.)By Implementing RUNNABLE interface

31
Thread Class
  • To implement Multi threading we have to override
    the run method of Thread class
  • Thread class is belongs to java.lang. package
  • Methods in this class
  • Start(),run(),sleep(),stop(),join()e.t.c.

32
Runnable Interface
  • This is an interface with only one method
  • That is RUN()
  • By implementing this interface we can get multi
    threading

33
CLIENT SIDE PROGRAM import
java.net. import java.io. public class
mclient public static void main(String a)
BufferedReader in PrintWriter pw
try Socket s new
Socket("localhost",118)
System.out.println("Enter name") in
new BufferedReader(new InputStreamReader(System.in
)) String msg in.readLine()
pw new PrintWriter(new OutputStreamWriter(s.ge
tOutputStream())) pw.println(msg"\n")
pw.flush() while(true)
readdata rd new readdata(s) Thread t
new Thread(rd) t.start()
34
msg in.readLine() if(msg.equals("quit"))
System.exit(0)
pw.println(msg) pw.flush()
catch(Exception e) System.out.println(e)
class readdata implements Runnable
public Socket s public readdata(Socket s)
this.s s
35
public void run()
BufferedReader br try
while(true) br new
BufferedReader(new InputStreamReader(s.getInputStr
eam())) String msg
br.readLine()
System.out.println(msg)
catch(Exception e)
System.out.println(e)
36
SERVER SIDE PROGRAM import java.net. import
java.io. public class mserver public
static Socket s new Socket10 public
static String user new String10 public
static int total public static void
main(String a) int i0 try
ServerSocket ss new ServerSocket(118)
while(true) si
ss.accept() BufferedReader br new
BufferedReader(new InputStreamReader(si.getInput
Stream())) String msg
br.readLine() useri msg
37
System.out.println(msg" connected") try
reqhandler req new reqhandler(si,i)
total i i Thread t new
Thread(req) t.start() catch(Exception
e) System.out.println(e)
catch(Exception e) System.out.println(
e)
38
class reqhandler implements Runnable public
int n public Socket s public
reqhandler(Socket soc,int i) s
soc n i public void run()
String msg ""
BufferedReader br,br1 PrintWriter pw
try while(true)
br1 new
BufferedReader(new InputStreamReader(System.in))
if((br1.readLine()).equals("quit")
) System.exit(0)
br new BufferedReader(new InputStreamReader(s.
getInputStream())) msg
br.readLine() i
39
if(msg.equals("quit")) mserver.total-- else
System.out.println(mserver.usern"-gt"msg) if(m
server.total -1) System.out.println("Ser
ver Disconnected") System.exit(0)
for(int k0kltmserver.totalk)
if(!mserver.userk.equals(mserver.usern)(!msg
.equals("quit"))) pw new
PrintWriter(new OutputStreamWriter(mserver.sk.ge
tOutputStream())) pw.println(mserver.usern
""msg"\n") pw.flush()
catch(Exception e)
40
OUTPUT
41
Output
42
(No Transcript)
43
Data Retrieval from a remote Database
44
Server
1. Request for data from database
2. Access to data base
Give response to client
Data base
Client
45
Server
Server side program
  • Listening to the port,
  • Establishing connections
  • Reading from and writing to the socket.

46
A socket is an end point for communication
between two machines
Server
ServerSocket ssocnew ServerSocket(1111)
This ServerSocket object is used to listen on a
port
47
Port is an address that identifies the particular
application in destination machine
192.256.17.25
Port 1111
48
Establishing connections
Server
Accepting the connection
Client
Socket csocssoc.accept()
Client socket object which is bound to same local
port(1111) The communication is done through the
new socket object
49
In Server program
BufferedReader fromc new BufferedReader(new
InputStreamReader(csoc.getInputStream()))
csoc.getInputStream
It reads input from socket object
PrintStream tocnew PrintStream(csoc.getOutputStre
am())
csoc.getOutputStream
It writes stream of data to socket object
50
In client program
PrintStream tosnew PrintStream(soc.getOutputStrea
m())
It writes stream of data to socket object

BufferedReader fromsnew BufferedReader(new
InputStreamReader(soc.getInputStream()))
It reads input from socket object
BufferedReader fromkbnew BufferedReader(new
InputStreamReader(System.in))
Takes the input from keyboard
51
Connecting to data base
Server
  • Load the Driver class

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
52
Server
getConnection()
Connection conn DriverManager.getConnection("jdb
codbcdns",userid",password")
53
Server
Ready to execute queries
interface
stmtconn.createStatement()
Statement
  • Statement object is created for executing the SQL
    queries

54
String queryfromkb.readLine()
Server
Pose a query
Send to server
tos.println(query)
Client
55
Server
queryfromc.readLine()
Client
Metadata
if(query.equalsIgnoreCase("quit")) break
ResultSetMetaData rsmdrs.getMetaData()
ResultSet rsstmt.executeQuery(query)
Interface
56
int noColrsmd.getColumnCount()
if(rs.next()) rsetnew StringBuffer("RESULT\n")
for(int i1iltnoColi) rset.append(rsmd.getCo
lumnLabel(i)"\t") rset.append("\n")
do for(int i1iltnoColi)
rset.append(rs.getString(i)"\t") rset.append("\
n") while(rs.next())
57
Server
toc.print(rset)
Client
queryfroms.readLine()
All the data retrieved is said to be returned to
the client through rset object
System.out.println(query)

Field 1 Field 2
xxxx yyyyy
zxzxzx zzzzz
58
Server
Client

conn.close()
59
Server side program import java.io. import
java.net. import java.sql. class rdbserver
public static void main(String args)
Connection connnull Statement stmtnull
ResultSet rsnull try
ServerSocket ssocnew ServerSocket(1111)
System.out.println("wait for client
connection\n") Socket csocssoc.accept()
if(csoc!null) System.out.println("cl
ient is connected")
60
BufferedReader fromcnew BufferedReader(new

InputStreamReader(csoc.getInputStream()))

PrintStream tocnew PrintStream(csoc.getOutputS
tream()) BufferedReader innew
BufferedReader(new InputStreamReader(System.in))
String query"" StringBuffer rsetnull
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
connDriverManager.getConnection("jdbcodbcvinod"
,"scott","tiger") stmtconn.createStatement()
do queryfromc.readLine()
System.out.println("client query
request"query) if(query.equalsIgnoreCase
("quit")) break rsstmt.executeQuer
y(query) ResultSetMetaData
rsmdrs.getMetaData() int
noColrsmd.getColumnCount()
if(rs.next()) rsetnew
StringBuffer("RESULT\n") for(int
i1iltnoColi) rset.append(rsmd.getColumnLabe
l(i)"\n") rset.append("\n")

61
Do for(int i1iltnoColi)
rset.append(rs.getString(i)"\t")
rset.append("\n") while(rs.next()) rset.append
("") toc.println(rset) while(!query.equalsI
gnoreCase("quit")) conn.close() catch(Excepti
on e) System.out.println(e.getMessage())

62
Clint side program import java.io. import
java.net. import java.sql. public class
rdbclient public static void main(String
args) System.out.println("connected to
serverdata") try Socket socnew
Socket("localhost",1111) PrintStream
tosnew PrintStream(soc.getOutputStream())
BufferedReader fromsnew BufferedReader(new

InputStreamReader(soc.getInputStream()))
BufferedReader fromkbnew BufferedReader(new

InputStreamReader(System.in))
String query"" System.out.println("conne
cted\n") System.out.print("enter query")
63
do queryfromkb.readLine()
tos.println(query) if(query.equalsIgnoreCase("qu
it")) break do queryfroms.readLine()
System.out.println(query) while(!query.starts
With("")) while(!query.equalsIgnoreCase("quit")
) catch(Exception e) System.out.println(e)

64
Server side output window
65
Clint side output window
66
SIMPLE MAIL TRANSFER PROTOCOL
67
PROGRAM
/import the packages needed for email and gui
support/ import java.net. import
java.io. import java.awt. import
java.awt.event. / This class defines methods
that display the gui and handle the sending of
mails to the Mail server. / public class
SMTP extends WindowAdapter implements
ActionListener private Button sendBut
new Button("Send Message") private Label
fromLabel new Label(" From ")
private Label toLabel new Label(" To
") private Label hostLabel new
Label("Host Name ") private Label
subLabel new Label(" Subject ")
private TextField fromTxt new TextField(25)
private TextField toTxt new TextField(25)
private TextField subTxt new
TextField(25) private TextField hostTxt
new TextField(25) private TextArea msgTxt
new TextArea() private Frame clientFrame
new Frame("SMTP Client")
68
/ Constructor with takes no parameters.
this constructor displays the window for the
user to assist in sending emails. /
public SMTP()
clientFrame.setLayout(new GridLayout(2,1))
Panel p1 new Panel()
p1.setLayout(new GridLayout(4,1))
Panel p11 new Panel()
p11.setLayout(new FlowLayout())
p11.add(hostLabel)
p11.add(hostTxt) Panel p12 new
Panel() p12.setLayout(new
FlowLayout()) p12.add(fromLabel)
p12.add(fromTxt)
Panel p13 new Panel()
p13.setLayout(new FlowLayout())
p13.add(toLabel) p13.add(toTxt)
Panel p14 new Panel()
p14.setLayout(new FlowLayout())
p14.add(subLabel) p14.add(subTxt)
69
p1.add(p11) p1.add(p12)
p1.add(p13) p1.add(p14)
Panel p2 new Panel()
p2.setLayout(new BorderLayout())
p2.add(msgTxt,BorderLayout.CENTER)
Panel p21 new Panel()
p21.setLayout(new FlowLayout())
p21.add(sendBut) p2.add(p21,BorderLayo
ut.SOUTH) clientFrame.add(p1)
clientFrame.add(p2)
clientFrame.setSize(400,500)
clientFrame.setVisible(true)
clientFrame.addWindowListener(this)
sendBut.addActionListener(this)
70
/ This method is triggered when the close
button of a window is closed. The
method exits the application. / public void
windowClosing(WindowEvent we)
clientFrame.setVisible(false)
System.exit(1) / This method is called
in response to button clicks. The
method reads the message to be sent, packs it in
a Message object and sends it to the
mail server. / public void actionPerformed(Actio
nEvent ae) try Socket snew
Socket(hostTxt.getText(),25) BufferedReader
brnew BufferedReader(new
InputStreamReader(s.getInputStrea
m())) PrintWriter pwnew PrintWriter(s.getOu
tputStream(),true) System.out.println("Conn
ection is established") pw.println("HELLO")
System.out.println(br.readLine())
pw.println("MAIL From"fromTxt.getText())
System.out.println(br.readLine())
pw.println("RCPT To"toTxt.getText())
71
System.out.println(br.readLine())
pw.println("DATA") pw.println(msgTxt.getText()"
\n.\n") System.out.println(br.readLine())
pw.println("QUIT") pw.flush() s.close()
System.out.println("Mail has been sent....")
catch(Exception e)
System.out.println("Connection Terminated")
/ This is the main
method . It instantiates an object of this
class (SMTPClient) and adds listeners for the
frame window and the buttons used in
the gui. / public static void main(String
args) SMTP client new
SMTP()
72
OUTPUT
73
(No Transcript)
74
Pop clients
75
POP Client
  • Short for Post Office Protocol, a protocol used
    to retrieve e-mail from a mail server. Most
    e-mail applications (sometimes called an e-mail
    client) use the POP protocol, although some can
    use the newer IMAP (Internet Message Access
    Protocol).
  • There are two versions of POP. The first, called
    POP2, became a standard in the mid-80's and
    requires SMTP to send messages. The newer
    version, POP3, can be used with or without SMTP.
    POP3 uses TCP/IP port 110.

76
  • With IMAP, all your mail stays on the server in
    multiple folders, some of which you have created.
    This enables you to connect to any computer and
    see all your mail and mail folders. In general,
    IMAP is great if you have a dedicated connection
    to the Internet or you like to check your mail
    from various locations.
  • With POP3 you only have one folder, the Inbox
    folder. When you open your mailbox, new mail is
    moved from the host server and saved on your
    computer. If you want to be able to see your old
    mail messages, you have to go back to the
    computer where you last opened your mail.
  • With POP3 "leave mail on server" only your email
    messages are on the server, but with IMAP your
    email folders are also on the server.

77
POP3 client application
78
Email Services SMTP/POP Protocols
  • Post Office Protocol (POP) and Simple Mail
    Transfer Protocol (SMTP) are involved in email
    services.
  • Users use an application called a Mail User Agent
    (MUA), or e-mail client to allow messages to be
    sent and places received messages into the
    client's mailbox.
  • In order to receive e-mail messages from an
    e-mail server, the e-mail client can use POP.
  • Sending e-mail from either a client or a server
    uses message formats and command strings defined
    by the SMTP protocol.

79
Mail Transfer Agent (MTA) Mail Delivery Agent
(MDA)

POP
SMTP
80
Server side Program
/POP Client gives the server name,username and
password,retrieve the mails and allow
manipulation of mailbox using POP
commands/ import java.io. import
java.net. import java.awt. import
javax.swing. import java.util. import
java.awt.event. class pop extends JFrame
implements ActionListener JPanel jp
JLabel lpadd,lpnum,lpass,lretr,luser
JTextField padd,pnum,user,retr,del
JPasswordField pass JTextArea receive
JScrollPane scrlp JButton
login,list,quit,retrv,dele Socket s
PrintWriter pw BufferedReader br
int nmesgs
81
pop() jpnew JPanel() jp.setLayout(n
ull) lpaddnew JLabel("port address") lpadd.se
tBounds(20,20,100,20) jp.add(lpadd) paddnew
JTextField() padd.setBounds(110,20,120,20) jp.
add(padd) lpnumnew JLabel("port
number") lpnum.setBounds(20,40,100,20) jp.add(
lpnum) pnumnew JTextField() pnum.setBounds(11
0,40,120,20) jp.add(pnum) loginnew
JButton("login") login.setBounds(20,100,210,20)
jp.add(login) login.addActionListener(this)
lusernew JLabel("user name") luser.setBounds(20
,60,100,20)
82
jp.add(luser) usernew
JTextField() user.setBounds(110,60,120,20) jp.
add(user) lpassnew JLabel("password") lpass.s
etBounds(20,80,100,20) jp.add(lpass) passnew
JPasswordField() pass.setBounds(110,80,120,20)
jp.add(pass) listnew JButton("list") list.se
tBounds(20,120,210,20) list.addActionListener(th
is) jp.add(list) retrvnew JButton("retrieve")
retrv.setBounds(130,145,130,20) jp.add(retrv)
retrv.addActionListener(this) delenew
JButton("delete") dele.setBounds(130,165,130,20)
jp.add(dele) dele.addActionListe
ner(this) lretrnew JLabel("enter the meg
numebr") lretr.setBounds(20,145,120,20)
83
jp.add(lretr)
retrnew JTextField() retr.setBounds(100,145,30,
20) retr.addActionListener(this) jp.add(retr)
delnew JTextField() del.setBounds(100,165,30,
20) del.addActionListener(this) jp.add(del)
receivenew JTextArea() receive.setEditable(fals
e) scrlpnew JScrollPane(receive) jp.add(scrlp
) scrlp.setBounds(20,200,300,200) quitnew
JButton("quit") quit.setBounds(130,410,80,30)
jp.add(quit) quit.addActionListener(this) setT
itle("Post Office Protocol") setSize(350,470)
show() this.getContentPane().add(jp) setVisibl
e(true)
84
public void actionPerformed(ActionEvent ae)
if(ae.getSource()login)
try snew
Socket(padd.getText(),Integer.parseInt(pnum.getTex
t()))
brnew BufferedReader(new InputStreamReader(s.
getInputStream())) pwnew PrintWriter(new
OutputStreamWriter(s.getOutputStream()),true)
receive.setText(br.readLine()"\n")
pw.println("user"user.getText()) receive.app
end(br.readLine()"\n") pw.println("pass"pass.g
etText()) receive.append(br.readLine()"\n")
catch(IOException e)
JOptionPane.showMessageDialog(new
JPanel(),"connection can not be
established")
85
if(ae.getSource()list) StringTokenizer
st String str pw.println("list") try
strbr.readLine() stnew
StringTokenizer(str) st.nextToken()
strst.nextToken()
nmesgsInteger.parseInt(str)1 for(int
i0iltnmesgsi) receive.append(br.readL
ine()"\n") receive.append("no of
messages " str "\n") catch(Exception
e) JOptionPane.showMessageDialog(new
JPanel(),e)
86
if(ae.getSource()retrv) String
kretr.getText().trim()
pw.println("RETR \n"k) int
lInteger.parseInt(k) try
String stbr.readLine()
if(lltnmesgslgt0) while(!st.equals("."
)) receive.append(s
t"\n")
stbr.readLine()
else
receive.append(st"\n")
retr.setText("")
87
catch(Exception e) JOptionPane.showMes
sageDialog(new JPanel(),e)
if(ae.getSource()quit) System.exit(0)
if(ae.getSource()dele) try
pw.println("dele"del.getText().trim())
nmesgs-- del.setText("") rec
eive.append(br.readLine()"\n")
catch(Exception e) JOptionPane.sho
wMessageDialog(new JPanel(),e)

88
public static void main(String args)
pop pnew pop()
89
Clint side program
import java.io. import java.net. import
java.applet. import java.awt. import
java.awt.event. import java.util. public
class POPClient extends Frame implements
ActionListener TextField user,pass,host,msgno
TextArea msgta Button signin,disp,prev,next,ex
it int no_of_msg,n String str BufferedReader
br1,br2 PrintWriter pw Socket
snull public POPClient() super("POP") u
sernew TextField(20) passnew
TextField(20) hostnew TextField(20)
90
msgnonew
TextField(20) msgtanew TextArea("",10,50) s
igninnew Button("LOGIN") dispnew
Button("DISPLAY") nextnew Button("NEXT") pr
evnew Button("PREVIOUS") exitnew
Button("EXIT") no_of_msg0 str" "
n0 Panel p1 new Panel() Panel p2
new Panel() Panel p3 new Panel() Panel p4
new Panel() setLayout(new
GridLayout(3,1)) setSize(400,400) p1.setLayo
ut(new GridLayout(4,1)) Panel p11 new
Panel() p11.add(new Label("User Name
")) p11.add(user) Panel p12 new
Panel() p12.add(new Label("Password
")) p12.add(pass)
91
Panel p13 new
Panel() p13.add(new Label("Host Name
")) p13.add(host) Panel p14 new
Panel() p14.add(signin) p1.add(p11) p
1.add(p12) p1.add(p13) p1.add(p14) p3.set
Layout(new GridLayout(1,1)) p3.add(msgta) p4
.setLayout(new GridLayout(3,1)) Panel p41
new Panel() p41.add(new Label("Enter message
number ")) p41.add(msgno) Panel p42 new
Panel() p42.add(disp) p42.add(new Label("
")) p42.add(prev) Panel p43 new
Panel() p43.add(next) p43.add(new Label("
")) p43.add(exit)
92
p4.add(p41) p4.add(p42) p4.add(p43) add(p
1) add(p4) add(p3) setVisible(true) pa
ss.setEchoChar('') signin.addActionListener(th
is) disp.addActionListener(this) prev.addAct
ionListener(this) next.addActionListener(this)
exit.addActionListener(this) public
void actionPerformed(ActionEvent
ae) try if(ae.getSource()signin)
snew Socket(host.getText(),110) br1ne
w BufferedReader(new InputStreamReader(s.getInputS
tream()))
93

pwnew PrintWriter(s.getOutputStream(),true)
msgta.append(br1.readLine()) System.out.pr
intln("1") pw.println("user
"user.getText()) System.out.println("2")
msgta.append("\n"br1.readLine()) pw.printl
n("PASS "pass.getText()) System.out.println(
"3") msgta.append("\n"br1.readLine()) p
w.println("list") strbr1.readLine() msg
ta.append("\n"str) StringTokenizer stnew
StringTokenizer(str) String
tmpstrst.nextToken() tmpstrst.nextToken()
no_of_msgInteger.parseInt(tmpstr) while(
!(br1.readLine().equals("."))) if(ae.getS
ource()disp) nInteger.parseInt(msgno.g
etText()) display()
94
if(ae.getSource()next) n
display() if(ae.getSource()prev) n--
display() if(ae.getSource()exit)
if(s!null) s.close() System.out.println("Conn
ection terminated....") System.exit(1) catc
h(Exception c) System.out.println(c)
95
void display() msgta.setText("")
msgno.setText(String.valueOf(n))
if(ngt0nltno_of_msg) System.out.println("N
"n) pw.println("retr "n) do
try strbr1.readLine()
catch (Exception e) System.out.println(
"msg"str) msgta.append("\n"str)
while(!str.equals(".")) else
msgta.setText("You have "no_of_msg" mails")

96
public static void main(String args) POPCli
ent pnew POPClient()
97
File Transfer Protocol
98
What is File Transfer Protocol (FTP)?
  • FTP is
  • a standard network protocol used to exchange and
    manipulate files over a TCP/IP-based network,
    such as the Internet.
  • built on a client-server architecture and
    utilizes separate control and data connections
    between the client and server applications.

99
What is File Transfer Protocol (FTP)?
  • FTP differs from other client-server
    applications, it establishes two connections
    between the hosts
  • The first one is a data transfer connection
    which does Data Transfer Process ( DTP )
  • The other is a control information connection
    which interprets FTP commands through Protocol
    Interpreter

100
(No Transcript)
101
What is FTP used for?
  • FTP is used to
  • Promote sharing of files (computer programs
    and/or data)
  • Transfer data reliably, and efficiently

102
  • CLIENT SIDE PROGRAM
  • import java.net.
  • import java.io.
  • public class ftpclient
  • public static void main (String args)
  • Socket s
  • BufferedReader in, br
  • PrintWriter pw
  • String spath,dpath
  • FileOutputStream fos
  • int c
  • try
  • s new Socket ("localhost",1111)
  • in new BufferedReader (new InputStreamReader
    (System.in))
  • br new BufferedReader (new InputStreamReader
    (s.getInputStream()))

103
  • pw new PrintWriter(s.getOutputStream(), true)
  • System.out.println("\nEnter Sourcepath to copy
    file ")
  • spath in.readLine()
  • System.out.println("\nEnter DestinationPath to
    transfer ")
  • dpath in.readLine()
  • fos new FileOutputStream(dpath)
  • pw.println (spath)
  • while ((cbr.read())!-1)
  • fos.write((char)c)
  • fos.flush()
  • System.out.println("File trasfer completed\n")
  • catch (Exception e)
  • System.out.println(e)

104
  • SERVER SIDE PROGRAM
  • import java.net.
  • import java.io.
  • public class ftpserver
  • public static void main(String args)
  • Socket s
  • ServerSocket server
  • FileInputStream fis
  • BufferedReader br
  • PrintWriter pw
  • String filename
  • int c
  • try
  • server new ServerSocket(1111)
  • System.out.println("Server waitfor for
    connection\n")

105
  • s server.accept()
  • System.out.println("Connection established\n")
  • br new BufferedReader(new InputStreamReader(s.ge
    tInputStream()))
  • pw new PrintWriter(s.getOutputStream())
  • filename br.readLine()
  • fis new FileInputStream(filename)
  • while ((cfis.read())!-1)
  • pw.print((char)c)
  • pw.flush()
  • System.out.println(filename " copied to
    destnation")
  • s.close()
  • catch(Exception e)
  • System.out.println(e)

106
Output
107
TELNET
108


  • In the very earliest days of internetworking, one
    of the most important problems that
    computer scientists needed to solve was how to
    allow someone operating one computer to access
    and use another as if he or she were connected to
    it locally. The protocol created to meet this
    need was called Telnet, and the effort to develop
    it was tied closely to that of the Internet and
    TCP/IP as a whole.
  • Telnet (teletype network) is a network protocol
    used on the Internet or local area networks to
    provide a bidirectional interactive
    communications facility. Typically, telnet
    provides access to a command-line interface on a
    remote host via a virtual terminal connection
    which consists of an 8-bit byte oriented data
    connection over the Transmission Control
    Protocol.

109
(No Transcript)
110
(No Transcript)
111
  • Program
  • import java.io.
  • import java.net.
  • import java.awt.
  • import java.awt.event.
  • public class telnet extends WindowAdapter
    implements ActionListener,KeyListener
  •  
  • public static Frame telFrame
  • public static Socket s
  • public static BufferedReader br null
  • public static PrintWriter pw null
  • public static telnet tnet
  • public static MenuBar mbar
  • public static Menu connectMenu
  • public static Menu helpMenu
  • public static MenuItem connect,disconnect,exit,
    help
  • public static TextArea msgArea
  • public static TextField statusArea

112
  • public static void main(String args)
  •   telFrame new Frame("Telnet")
  • msgArea new TextArea()
  • statusArea new TextField()
  • Panel p new Panel()
  • p.setLayout(new BorderLayout())
  • mbar new MenuBar()
  • connectMenu new Menu("Connect")
  • connectMenu.add(connect new
    MenuItem("Connect"))
  • connectMenu.add(disconnect new
    MenuItem("Disconnect"))
  • connectMenu.add(exit new
    MenuItem("Exit"))
  • mbar.add(connectMenu)
  • helpMenu new Menu("Help")
  • helpMenu.add(help new MenuItem("help"))
  • //helpMenu.add(more new MenuItem("More.."))
  • mbar.add(helpMenu)
  • connect.addActionListener(new telnet())
  • disconnect.addActionListener(new telnet())

113
  • //more.addActionListener(new Telnet())
  •   msgArea.addKeyListener(new telnet())
  •   p.add(msgArea,BorderLayout.CENTER)
  • p.add(statusArea,BorderLayout.SOUTH)
  •   telFrame.setSize(450,350)
  • telFrame.setMenuBar(mbar)
  • telFrame.add(p)
  • telFrame.setVisible(true)
  • telFrame.addWindowListener(new telnet())
  • public void windowClosing(WindowEvent we)
  • telFrame.setVisible(false)
  • System.exit(0)
  • public void keyPressed(KeyEvent ke)
  • public void keyReleased(KeyEvent ke)

114
  • public void keyTyped(KeyEvent ke)
  • if(ke.getKeyChar()
    KeyEvent.VK_ENTER)
  • System.out.println(command)
  • pw.println(command)
  • command ""
  • else if(ke.getKeyChar() ! KeyEvent.VK_SHIFT)
  • command command ke.getKeyChar()
  • public void actionPerformed(ActionEvent ae)
  • String str ae.getActionCommand()
  • if(str.equals("Exit"))
  • System.exit(0)
  • if(str.equals("Connect"))
  • new ConnectFrame()
  • else if(str.equals("Disconnect"))
  • if(!(snull))
  • System.out.println("in
    disconnecting...")

115
  • System.out.println("Connection
    terminated")
  • statusArea.setText("Connection
    terminated")
  • try
  • s.close()
  • s null
  • catch(Exception
    e)
  • System.out.println("closing
    socket.")
  • else
  • new HelpFrame()
  • public void makeConnection()
  • try
  • s new Socket(ConnectFrame.host.getText().trim
    (),Integer.parseInt(ConnectFrame.port.getText().tr
    im()))

116
  • br new BufferedReader(new InputStreamReader(s.ge
    tInputStream()))
  • pw new PrintWriter(s.getOutput
    Stream(),true)
  • statusArea.setText("Connection
    Established")
  • new ReadThrd(msgArea,statusArea,
    br)
  • catch(Exception e)
  • System.out.println(e)
  • statusArea.setText("Connection
    Failed")
  • class ReadThrd extends Thread
  •  
  • TextArea msgArea
  • TextField statusArea
  • BufferedReader br
  • ReadThrd(TextArea msgArea,TextField
    statusArea,BufferedReader br)
  • super("reading data thread")
  • this.msgArea msgArea

117
this.statusArea statusArea
this.br br start() public
void run() try int off 0
while(true)
String reply br.readLine() if(reply
null) msgArea.append("\n\n----
----The remote host is not responding--------\n\n"
) break

msgArea.append(reply"\n")
catch(Exception e)
System.out.println(e)  
118
  • class ConnectFrame extends WindowAdapter
    implements ActionListener
  •  
  • Frame conFrame
  • public static TextField host,port
  • Button connect,cancel
  • public ConnectFrame()
  • conFrame new Frame("Connecting....")
  • host new TextField(10)
  • port new TextField(10)
  • connect new Button("Connect")
  • cancel new Button("Cancel")
  •  
  • Panel p1 new Panel()
  • p1.add(new Label("Remote Host "))
  • p1.add(host)
  •  
  • Panel p2 new Panel()
  • p2.add(new Label("Port Number "))
  • p2.add(port)

119
  • Panel p new Panel()
  • p.setLayout(new GridLayout(3,1))
  • p.add(p1)
  • p.add(p2)
  • p.add(p3)
  •  
  • connect.addActionListener(this)
  • cancel.addActionListener(this)
  •  
  • conFrame.setSize(250,200)
  • conFrame.add(p)
  • conFrame.setVisible(true)
  • conFrame.addWindowListener(this)

120
  • public void actionPerformed(ActionEvent ae)
  • telnet tnet new telnet()
  • String str ae.getActionCommand()
  • if(str.equals("Cancel"))
  • conFrame.setVisible(false)
  • else if(str.equals("Connect"))
  • conFrame.setVisible(false)
  • tnet.makeConnection()
  • public void windowClosing(WindowEvent we)
  • conFrame.setVisible(false)

121
  • class HelpFrame extends WindowAdapter
  • Frame helpFrame
  • public HelpFrame()
  • helpFrame new Frame("Telnet Help")
  • TextArea helpTxt new
    TextArea()
  • helpTxt.setEditable(false)
  • helpTxt.setText("Telnet help")
  • helpFrame.add(helpTxt)
  • helpFrame.setSize(300,400)
  • helpFrame.setVisible(true)
  • helpFrame.addWindowListener(this)
  • public void windowClosing(WindowEvent we)
  • helpFrame.setVisible(false)

122
OUTPUT
123
(No Transcript)
124
Trivial File Transfer Protocol
125
WHAT IS TFTP
  • Trivial File Transfer Protocol (TFTP) is a file
    transfer protocol, with the functionality of a
    very basic form of File Transfer Protocol (FTP)
  • It was first defined in 1980.

126
INFORMATION ABOUT TFTP
  • It is a simple protocol to transfer files. It
    has been implemented on top of the User Datagram
    Protocol (UDP) using port number 69.
  • TFTP only reads and writes files (or mail)
    from/to a remote server. It cannot list
    directories, and currently has no provisions for
    user authentication.

127
  • TFTP supports three different transfer modes,
    "netascii", "octet" and "mail", with the first
    two corresponding to the "ASCII" and "image"
    (binary) modes of the FTP protocol, and the third
    was made obsolete by RFC 1350.
  • TFTP is based in part on the earlier protocol
    EFTP, which was part of the PUP protocol suite.

128
USES
  • TFTP is used to read files from, or write files
    to, a remote server.
  • Due to the lack of security, it is dangerous over
    the open Internet. Thus, TFTP is generally only
    used on private, local networks.

129
LIMITS
  • TFTP cannot list directory contents.
  • TFTP has no authentication or encryption
    mechanisms.
  • TFTP allows big data packets which may burst and
    cause delay in transmission.
  • TFTP cannot download files larger than 1
    Terabyte.

130
  • Socket Programming
  • A socket is one end-point of a
    two-way communication link between two programs
    running on the network. Socket classes are used
    to represent the connection between a client
    program and a server program. The java.net
    package provides two classes--Socket and Server
    Socket--that implement the client side of the
    connection and the server side of the connection,
    respectively.

131
  • File Transfer Protocol
  • FTP is used to transfer files
    between computers on a network. You can use FTP
    to exchange files between computer accounts,
    transfer files between an account and a desktop
    computer.
  • Trivial File Transfer Protocol
  • The Trivial File Transfer Protocol (TFTP)
    allows a local host to obtain files from a remote
    host but does not provide reliability or
    security. It uses the fundamental packet delivery
    services offered by UDP.

132
Difference between FTP and TFTP
  • FTP provides minimal security through user logins
  • FTP provides a reliable service through its use
    of TCP
  • FTP uses two connections
  • 1.Data transfer
  • 2. Control information
  • FTP uses plain text channel
  • TFTP does not use logins
  • TFTP does not since it uses UDP
  • TFTP uses one connection (stop and wait)

133
  • Datagram packet
  • Datagram packets are used to
    implement a connectionless packet delivery
    service. Each message is routed from one machine
    to another based solely on information contained
    within that packet. Multiple packets sent from
    one machine to another might be routed
    differently, and might arrive in any order.
    Packet delivery is not guaranteed.
  • InputStreamReader
  • An InputStreamReader is a bridge
    from byte streams to character streams It reads
    bytes and decodes them into characters using a
    specified charset

134
SERVER SIDE PROGRAM import java.io. import
java.net. import java.lang. public class
tftps public static void main(String args)
throws Exception DatagramSocket dsnew
DatagramSocket(1500) byte snew
byte1024 DatagramPacket dpnew
DatagramPacket(s,1024) ds.receive(dp)
String datanew String(dp.getData(),0,dp.getLength
()) int count0 System.out.println("ENTER
THE FILE NAME TO TRANFER" data)
FileInputStream fsnew FileInputStream (data)
while(fs.available()!0)
if(fs.available()lt1024) countfs.available()
)
135
else count1024 snew bytecount
fs.read(s dpnew DatagramPacket(s,s.length,Ine
tAddress.getLocalHost(),1501)
ds.send(dp) fs.close() snew
byte3 s"".getBytes()
ds.send(newDatagramPacket(s,s.length,InetAddress.g
etLocalHost(),1501)) ds.close()
136
CLIENT SIDE PROGRAM import java.io. import
java.net. import java.lang. public class
tftpc public static void main(String args)
throws Exception DatagramSocket dsnew
DatagramSocket(1501) BufferedReader
inputnewBufferedReader(new InputStreamReader(Sys
tem.in)) System.out.println("ENTER THE FILE
NAME TO SAVE") String fileinput.readLine()
FileOutputStream
fosnew FileOutputStream(file) System.out.print
ln("ENTER THE FILE NAME TO TRANFER") fileinpu
t.readLine() byte snew bytefile.length()
sfile.getBytes()
137
String
datanull ds.send(new DatagramPacket(s,s.length
,InetAddress.getLocalHost(),1500)) while(true)
snew byte1024 DatagramPacket dpnew
DatagramPacket(s,1024) ds.receive(dp) datan
ew String(dp.getData(),0,dp.getLength()) if(da
ta.equals("")) break fos.write(data.getB
ytes()) fos.close() ds.close()
138
Server side output
Client side output
139
Http
Hyper Text Transfer protocol
140
Client/Server
  • A server is any thing that has some resource that
    can be shared.
  • Compute servers
  • Print server
  • Disk servers
  • Web servers
  • A client is simply any other entity that wants to
    gain access to a
  • particular server.

141
InetAddress
  • This class is used to encapsulate numerical IP
    address and
  • domain name for that address
  • This class has no visible constructors so to
    create InetAddress object we have to use one
    of the available factory methods.
  • Factory methods are static methods in a class
    return an instance of that class
  • static InetAddress getLocalHost() throws
    UnknownHostException
  • static InetAddress getByName(String hostName)

  • throws UnknownHostException
  • static InetAddress getAllByName(String
    hostName)

  • throws UnknownHostException

142
InetAddress example
import java.net. class InetAddressTest
public static void main(String args) throws
UnknownHostException InetAddress
AddressInetAddress.getLocalHost()
System.out.println(Address) AddressInetAddress
.getByName("yahoo.com") System.out.println(Addr
ess) InetAddress swInetAddress.getAllByName(
"www.nba.com") for(int i0iltsw.lengthi)
System.out.println(swi)
143
HTTP Server side program import
java.io. import java.net. import
java.lang. public class https public static
void main(String args) throws Exception
ServerSocket ssocnew ServerSocket(1111)
System.out.println("Server waits for
client\n") Socket sossoc.accept()
System.out.println("client connected to Server
\n") BufferedReader brnew
BufferedReader(new

InputStreamReader(so.getInputStream()))
PrintWriter pwnew PrintWriter(so.getOutputStream(
),true) BufferedReader innew
BufferedReader(new InputStreamReader(System.in
))
144
int ch do
chInteger.parseInt(br.readLine())
String file byte linenull File
f switch(ch)
case 1 System.out.println("1.head")
filebr.readLine() fnew
File(file) int indexfile.lastIndexOf(".
") String typefile.substring(index1)
pw.println(type)
long lengthf.length()
pw.println(length)
break case 2 System.out.println("2.pos
t") filebr.readLine()
System.out.println("message from
client\n") System.out.println(file) bre
ak
145
case 3
System.out.println("3.get")
filebr.readLine() FileInputStream
fsnew FileInputStream(file)
while(fs.available()!0)
if(fs.available()lt1024) linenew
bytefs.available() else linenew
byte1024 fs.read(line)
filenew String(line)
pw.println(file) pw.println("")
fs.close() break
case 4 System.out.println("4.d
elete") filebr.readLine() fnew
File(file) f.delete() break default
System.out.println("5.exit") System.exit(0)

146
while(chlt4) so.close() ssoc.close()

147
HTTP Server side program import
java.io. import java.net. import
java.lang. public class httpc public static
void main(String args) throws Exception
Socket socnew Socket("localhost",1111)
BufferedReader brnew BufferedReader(new
InputStreamReader(soc.getInputStream()))
PrintWriter pwnew PrintWriter(soc.getOutputStream
(),true) BufferedReader innew
BufferedReader(new InputStreamReader(System.in))
System.out.println("server is
connected\n") int ch do
System.out.println("COMMANDS")
System.out.println("\n 1.head \n 2.post \n 3.get
\n4.delete\n 5.exit")
148
System.out.println("ENTER UR CHOICE")
chInteger.parseInt(in.readLine()) byte
linenull String file switch(ch)
case 1pw.println("1") filein.readLine() pw.
println(file) String typebr.readLine() String
lengthbr.readLine() System.out.println("FILE"
file"\nTYPE"type"\nLEN GTH"length) break
case 2 pw.println("2")
System.out.println("enter text to post")
filein.readLine() pw.println(file)
System.out.println("text is posted at
server") break
149
case 3pw.println("3")
System.out.println("enter file name to get")
filein.readLine() pw.println(file)
System.out.println("enter file name to
save") filein.readLine()
FileOutputStream fsnew FileOutputStream(file)
while(true) String
sbr.readLine() if(s.equals(""))
break int counts.length()
if(countlt1024) linenew byte1024
lines.getBytes()
fs.write(line)
fs.close() System.out.println("\n file
successfully tranfered") break
150
case 4 pw.println("4")
System.out.println("enter the file to
delete") filein.readLine()
pw.println(file) System.out.println("give
n file deleted") break
default pw.println("5")
System.exit(0)
while(chlt4) soc.close()
151
Clint side Output window
152
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com