151

Network Programming Lab.ppt

  • Upload
    preetha

  • View
    233

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Network Programming Lab.ppt
Page 2: Network Programming Lab.ppt

import java.io.*;import java.net.*;class wkports{ public static void main(String args[]) { for(int i=100;i<200;i++) { try { Socket s=new 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()); } } } }

Program:

Page 3: Network Programming Lab.ppt

Output:-

Page 4: Network Programming Lab.ppt

One to One Chat Application

Page 5: Network Programming Lab.ppt

•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

Page 6: Network Programming Lab.ppt

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”.

Page 7: Network Programming Lab.ppt

Socket Programming Exception Handling I/O and StreamClasses

Page 8: Network Programming Lab.ppt

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.

Page 9: Network Programming Lab.ppt

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

Page 10: Network Programming Lab.ppt

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

Page 11: Network Programming Lab.ppt

try { code }

CATCH BLOCKcatch (Exception ex){

<do something with ex>}

catch A method can catch an exception by providing an

exception handler for that type of exception.

Page 12: Network Programming Lab.ppt

Client side program:import java.io.*;import java.net.*;import java.lang.*;public class chatclient1{ public static void main(String args[]) throws IOException{Socket csoc=null;String host;if(args.length>0)host=args[0];elsehost="localhost";PrintWriter pout=null;BufferedReader bin=null; try{csoc=new Socket(host,7);pout=new PrintWriter(csoc.getOutputStream(),true);bin=new BufferedReader(new InputStreamReader(csoc.getInputStream()));}

Page 13: Network Programming Lab.ppt

catch(UnknownHostException e) {System.err.println("Unknownhost");System.exit(1);}catch(IOException e){}BufferedReader in=new BufferedReader(new InputStreamReader(System.in));String input;while(true){input=in.readLine();pout.println(input);String msg=bin.readLine();System.out.println("client :"+msg);if(msg.equals("bye"))break;}in.close();pout.close();bin.close();csoc.close();}}

Page 14: Network Programming Lab.ppt

import java.io.*;import java.net.*;import java.lang.*;public class chatserver1{public static void main(String args[]) throws IOException{ServerSocket ssoc=null;try{ssoc=new ServerSocket(7);}catch(IOException e){System.err.println("No connection established");System.exit(1);}Socket csoc=null;

try{csoc=ssoc.accept();}

Server side program:

Page 15: Network Programming Lab.ppt

catch(IOException e){System.err.println("Not accepted");System.exit(1);}PrintWriter pw=new PrintWriter(csoc.getOutputStream(),true);BufferedReader br=new BufferedReader(new InputStreamReader(csoc.getInputStream()));String inline;String outline;try{DataInputStream din=new DataInputStream(System.in);while(true){inline=br.readLine();System.out.println("Server :"+inline);outline=din.readLine();pw.println(outline);if(outline.equals("bye"))break;}}

Page 16: Network Programming Lab.ppt

catch(Exception e){System.err.println(e);}pw.close();br.close();csoc.close();ssoc.close();}}

Page 17: Network Programming Lab.ppt

Server side output window:

Clint side output window:

Page 18: Network Programming Lab.ppt
Page 19: Network Programming Lab.ppt

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.

Page 20: Network Programming Lab.ppt

Connections Between Systems

Page 21: Network Programming Lab.ppt

Socket communication Exception Handling IO Multi Threading

Page 22: Network Programming Lab.ppt

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.

Page 23: Network Programming Lab.ppt

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

 

Page 24: Network Programming Lab.ppt

Print Writer:

Print formatted representations of objects to a text-output stream.

public PrintWriter(OutputStream out,boolean autoFlush)

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.

Page 25: Network Programming Lab.ppt

InputStream Returns an input stream for socket. This method is Belongs socket class. Socket class is belongs to java.net.

PackageOutPutStream Returns an output stream for socket.

Page 26: Network Programming Lab.ppt

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.

Page 27: Network Programming Lab.ppt

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

Page 28: Network Programming Lab.ppt

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.

Page 29: Network Programming Lab.ppt

We can implement multi threading using java in 2 ways

1.)By inheriting Thread class or 2.)By Implementing RUNNABLE

interface

Page 30: Network Programming Lab.ppt

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.

Page 31: Network Programming Lab.ppt

This is an interface with only one method

That is RUN() By implementing this interface we can

get multi threading

Page 32: Network Programming Lab.ppt

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.getOutputStream())); pw.println(msg+"\n"); pw.flush(); while(true) {

readdata rd = new readdata(s);Thread t = new Thread(rd);t.start();

Page 33: Network Programming Lab.ppt

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; }

Page 34: Network Programming Lab.ppt

public void run() {

BufferedReader br;try{

while(true) { br = new BufferedReader(new InputStreamReader(s.getInputStream()));

String msg = br.readLine(); System.out.println(msg); }

}catch(Exception e){

System.out.println(e);}

} }

Page 35: Network Programming Lab.ppt

SERVER SIDE PROGRAM :

import java.net.*;import java.io.*;public class mserver{ public static Socket s[] = new Socket[10]; public static String user[] = new String[10]; public static int total; public static void main(String a[]) { int i=0; try { ServerSocket ss = new ServerSocket(118); while(true) { s[i] = ss.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(s[i].getInputStream())); String msg = br.readLine(); user[i] = msg;

Page 36: Network Programming Lab.ppt

System.out.println(msg+" connected") ; try { reqhandler req = new reqhandler(s[i],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); }}}

Page 37: Network Programming Lab.ppt

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

Page 38: Network Programming Lab.ppt

if(msg.equals("quit")) mserver.total--;else System.out.println(mserver.user[n]+"->"+msg);if(mserver.total == -1) { System.out.println("Server Disconnected"); System.exit(0); }for(int k=0;k<=mserver.total;k++) if(!mserver.user[k].equals(mserver.user[n])&&(!msg.equals("quit"))) { pw = new PrintWriter(new OutputStreamWriter(mserver.s[k].getOutputStream())); pw.println(mserver.user[n]+":"+msg+"\n"); pw.flush(); } }}}catch(Exception e) { } }}

Page 39: Network Programming Lab.ppt

OUTPUT:

Page 40: Network Programming Lab.ppt

Output:

Page 41: Network Programming Lab.ppt
Page 42: Network Programming Lab.ppt
Page 43: Network Programming Lab.ppt

Data base

1. Request for data from database2. Access to data base

Give response to client

Server

Client

Page 44: Network Programming Lab.ppt

Server

Listening to the port, Establishing connectionsReading from and writing to the socket.

Server side program:

Page 45: Network Programming Lab.ppt

ServerSocket ssoc=new ServerSocket(1111);

Server

This ServerSocket object is used to listen on a port

A socket is an end point for communication between two machines

Page 46: Network Programming Lab.ppt

Port is an address that identifies the particular application in destination machine

Port: 1111

192.256.17.25

Page 47: Network Programming Lab.ppt

Socket csoc=ssoc.accept();

Server

Client

Accepting the connection

Client socket object which is bound to same local port(1111) The communication is done through the new socket object

Establishing connections

Page 48: Network Programming Lab.ppt

BufferedReader fromc= new BufferedReader(new InputStreamReader(csoc.getInputStream()))

csoc.getInputStream: It reads input from socket object

PrintStream toc=new PrintStream(csoc.getOutputStream());

csoc.getOutputStream: It writes stream of data to socket object

In Server program:

Page 49: Network Programming Lab.ppt

PrintStream tos=new PrintStream(soc.getOutputStream());

BufferedReader froms=new BufferedReader(new InputStreamReader(soc.getInputStream()));

BufferedReader fromkb=new BufferedReader(new InputStreamReader(System.in));

It writes stream of data to socket object

It reads input from socket object

Takes the input from keyboard

In client program:

Page 50: Network Programming Lab.ppt

Server

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connecting to data base

Load the Driver class

Page 51: Network Programming Lab.ppt

Server getConnection()

Connection conn = DriverManager.getConnection("jdbc:odbc:dns",“userid",“password");

Page 52: Network Programming Lab.ppt

Server

stmt=conn.createStatement();Statement

Statement object is created for executing the SQL queries

interface

Ready to execute queries

Page 53: Network Programming Lab.ppt

Client

ServerPose a query

tos.println(query);

String query=fromkb.readLine();

Send to server

Page 54: Network Programming Lab.ppt

query=fromc.readLine();

if(query.equalsIgnoreCase("quit"))break;

Client

Server

ResultSetMetaData rsmd=rs.getMetaData();

Interface

Metadata

ResultSet rs=stmt.executeQuery(query);

Page 55: Network Programming Lab.ppt

int noCol=rsmd.getColumnCount();

if(rs.next()){rset=new StringBuffer("RESULT:\n");for(int i=1;i<=noCol;i++)rset.append(rsmd.getColumnLabel(i)+"\t");rset.append("\n");}do{for(int i=1;i<=noCol;i++) rset.append(rs.getString(i)+"\t");rset.append("\n");}while(rs.next());

Page 56: Network Programming Lab.ppt

Client

Server

All the data retrieved is said to be returned to the client through rset object

query=froms.readLine();

toc.print(rset);

System.out.println(query);

Field 1 Field 2xxxx yyyyyzxzxzx zzzzz

Page 57: Network Programming Lab.ppt

conn.close();

Client

Server

Page 58: Network Programming Lab.ppt

Server side program:

import java.io.*;import java.net.*;import java.sql.*;class rdbserver{ public static void main(String args[]) { Connection conn=null; Statement stmt=null; ResultSet rs=null; try { ServerSocket ssoc=new ServerSocket(1111); System.out.println("wait for client connection:\n"); Socket csoc=ssoc.accept(); if(csoc!=null) System.out.println("client is connected:");

Page 59: Network Programming Lab.ppt

BufferedReader fromc=new BufferedReader(new InputStreamReader(csoc.getInputStream())); PrintStream toc=new PrintStream(csoc.getOutputStream()); BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String query=""; StringBuffer rset=null; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn=DriverManager.getConnection("jdbc:odbc:vinod","scott","tiger"); stmt=conn.createStatement(); do { query=fromc.readLine(); System.out.println("client query request:"+query); if(query.equalsIgnoreCase("quit")) break; rs=stmt.executeQuery(query); ResultSetMetaData rsmd=rs.getMetaData(); int noCol=rsmd.getColumnCount(); if(rs.next()) { rset=new StringBuffer("RESULT:\n"); for(int i=1;i<=noCol;i++)

rset.append(rsmd.getColumnLabel(i)+"\n"); rset.append("\n"); }

Page 60: Network Programming Lab.ppt

Do{ for(int i=1;i<=noCol;i++) rset.append(rs.getString(i)+"\t"); rset.append("\n");}while(rs.next());rset.append("");toc.println(rset);}while(!query.equalsIgnoreCase("quit")); conn.close();}catch(Exception e){ System.out.println(e.getMessage()); } }}

Page 61: Network Programming Lab.ppt

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 soc=new Socket("localhost",1111); PrintStream tos=new PrintStream(soc.getOutputStream()); BufferedReader froms=new BufferedReader(new InputStreamReader(soc.getInputStream())); BufferedReader fromkb=new BufferedReader(new InputStreamReader(System.in));

String query=""; System.out.println("connected:\n"); System.out.print("enter query:");

Page 62: Network Programming Lab.ppt

do{ query=fromkb.readLine(); tos.println(query); if(query.equalsIgnoreCase("quit")) break; do { query=froms.readLine(); System.out.println(query); } while(!query.startsWith(""));}while(!query.equalsIgnoreCase("quit"));}catch(Exception e){ System.out.println(e);}}}

Page 63: Network Programming Lab.ppt

Server side output window:

Page 64: Network Programming Lab.ppt

Clint side output window:

Page 65: Network Programming Lab.ppt
Page 66: Network Programming Lab.ppt

/*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");

Page 67: Network Programming Lab.ppt

/*** 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);

Page 68: Network Programming Lab.ppt

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,BorderLayout.SOUTH);

clientFrame.add(p1); clientFrame.add(p2); clientFrame.setSize(400,500); clientFrame.setVisible(true); clientFrame.addWindowListener(this); sendBut.addActionListener(this); }

Page 69: Network Programming Lab.ppt

/** * 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(ActionEvent ae) { try { Socket s=new Socket(hostTxt.getText(),25); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter pw=new PrintWriter(s.getOutputStream(),true); System.out.println("Connection 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());

Page 70: Network Programming Lab.ppt

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(); } }

Page 71: Network Programming Lab.ppt
Page 72: Network Programming Lab.ppt
Page 73: Network Programming Lab.ppt
Page 74: Network Programming Lab.ppt

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.

Page 75: Network Programming Lab.ppt

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.

Page 76: Network Programming Lab.ppt
Page 77: Network Programming Lab.ppt

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.

Page 78: Network Programming Lab.ppt

POP

SMTP

Page 79: Network Programming Lab.ppt

/*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;

Page 80: Network Programming Lab.ppt

pop() {

jp=new JPanel();jp.setLayout(null);lpadd=new JLabel("port address");lpadd.setBounds(20,20,100,20);jp.add(lpadd);padd=new JTextField();padd.setBounds(110,20,120,20);jp.add(padd);lpnum=new JLabel("port number");lpnum.setBounds(20,40,100,20);jp.add(lpnum);pnum=new JTextField();pnum.setBounds(110,40,120,20);jp.add(pnum);login=new JButton("login");login.setBounds(20,100,210,20);jp.add(login);login.addActionListener(this);luser=new JLabel("user name");luser.setBounds(20,60,100,20);

Page 81: Network Programming Lab.ppt

jp.add(luser);user=new JTextField();user.setBounds(110,60,120,20);jp.add(user);lpass=new JLabel("password");lpass.setBounds(20,80,100,20);jp.add(lpass);pass=new JPasswordField();pass.setBounds(110,80,120,20);jp.add(pass);list=new JButton("list");list.setBounds(20,120,210,20);list.addActionListener(this);jp.add(list);retrv=new JButton("retrieve");retrv.setBounds(130,145,130,20);jp.add(retrv);retrv.addActionListener(this);dele=new JButton("delete");dele.setBounds(130,165,130,20);jp.add(dele);

dele.addActionListener(this);lretr=new JLabel("enter the meg numebr");lretr.setBounds(20,145,120,20);

Page 82: Network Programming Lab.ppt

jp.add(lretr); retr=new JTextField();

retr.setBounds(100,145,30,20);retr.addActionListener(this);jp.add(retr);del=new JTextField();del.setBounds(100,165,30,20);del.addActionListener(this);jp.add(del);receive=new JTextArea();receive.setEditable(false);scrlp=new JScrollPane(receive);jp.add(scrlp);scrlp.setBounds(20,200,300,200);quit=new JButton("quit");quit.setBounds(130,410,80,30);jp.add(quit);quit.addActionListener(this);setTitle("Post Office Protocol");setSize(350,470);show();this.getContentPane().add(jp);setVisible(true);

}

Page 83: Network Programming Lab.ppt

public void actionPerformed(ActionEvent ae) { if(ae.getSource()==login) {

try { s=new Socket(padd.getText(),Integer.parseInt(pnum.getText()));

br=new BufferedReader(new InputStreamReader(s.getInputStream()));

pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true); receive.setText(br.readLine()+"\n");

pw.println("user"+user.getText());receive.append(br.readLine()+"\n");pw.println("pass"+pass.getText());receive.append(br.readLine()+"\n");

}catch(IOException e){ JOptionPane.showMessageDialog(new JPanel(),"connection can not

be established");}

}

Page 84: Network Programming Lab.ppt

if(ae.getSource()==list) {

StringTokenizer st;String str;pw.println("list");try{ str=br.readLine(); st=new StringTokenizer(str); st.nextToken(); str=st.nextToken(); nmesgs=Integer.parseInt(str)+1; for(int i=0;i<nmesgs;i++) receive.append(br.readLine()+"\n"); receive.append("no of messages :" + str + "\n"); }catch(Exception e){ JOptionPane.showMessageDialog(new JPanel(),e);}

}

Page 85: Network Programming Lab.ppt

if(ae.getSource()==retrv){ String k=retr.getText().trim();

pw.println("RETR \n"+k); int l=Integer.parseInt(k); try {

String st=br.readLine(); if(l<nmesgs&&l>0)

{ while(!st.equals("."))

{receive.append(st+"\n");

st=br.readLine(); } } else

{ receive.append(st+"\n");

}retr.setText("");

}

Page 86: Network Programming Lab.ppt

catch(Exception e) {

JOptionPane.showMessageDialog(new JPanel(),e); }

}if(ae.getSource()==quit)System.exit(0);if(ae.getSource()==dele){ try {

pw.println("dele"+del.getText().trim()); nmesgs--;

del.setText("");receive.append(br.readLine()+"\n");

} catch(Exception e) {

JOptionPane.showMessageDialog(new JPanel(),e); }

} }

Page 87: Network Programming Lab.ppt

public static void main(String args[]) {

pop p=new pop(); }}

Page 88: Network Programming Lab.ppt

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,exit;int no_of_msg,n;String str;BufferedReader br1,br2;PrintWriter pw;Socket s=null;public POPClient(){

super("POP");user=new TextField(20);pass=new TextField(20);host=new TextField(20);

Page 89: Network Programming Lab.ppt

msgno=new TextField(20);msgta=new TextArea("",10,50);signin=new Button("LOGIN");disp=new Button("DISPLAY");next=new Button("NEXT");prev=new Button("PREVIOUS");exit=new Button("EXIT");no_of_msg=0;str=" "; n=0;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.setLayout(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);

Page 90: Network Programming Lab.ppt

Panel p13 = new Panel();p13.add(new Label("Host Name : "));p13.add(host);Panel p14 = new Panel();p14.add(signin); p1.add(p11);p1.add(p12);p1.add(p13);p1.add(p14);p3.setLayout(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);

Page 91: Network Programming Lab.ppt

p4.add(p41);p4.add(p42);p4.add(p43);add(p1);add(p4);add(p3);setVisible(true);pass.setEchoChar('*');signin.addActionListener(this);disp.addActionListener(this);prev.addActionListener(this);next.addActionListener(this);exit.addActionListener(this);

}

public void actionPerformed(ActionEvent ae){

try{

if(ae.getSource()==signin){

s=new Socket(host.getText(),110);br1=new BufferedReader(new

InputStreamReader(s.getInputStream()));

Page 92: Network Programming Lab.ppt

pw=new PrintWriter(s.getOutputStream(),true);msgta.append(br1.readLine());System.out.println("1");pw.println("user "+user.getText());System.out.println("2");msgta.append("\n"+br1.readLine());pw.println("PASS "+pass.getText());System.out.println("3");msgta.append("\n"+br1.readLine());pw.println("list");str=br1.readLine();msgta.append("\n"+str);StringTokenizer st=new StringTokenizer(str);String tmpstr=st.nextToken();tmpstr=st.nextToken();no_of_msg=Integer.parseInt(tmpstr);while(!(br1.readLine().equals(".")));

}if(ae.getSource()==disp){

n=Integer.parseInt(msgno.getText());display();

}

Page 93: Network Programming Lab.ppt

if(ae.getSource()==next){ n++; display();}if(ae.getSource()==prev){ n--; display();}if(ae.getSource()==exit){ if(s!=null) s.close(); System.out.println("Connection terminated...."); System.exit(1);}}catch(Exception c){ System.out.println(c);}}

Page 94: Network Programming Lab.ppt

void display() { msgta.setText(""); msgno.setText(String.valueOf(n)); if(n>0&&n<=no_of_msg) { System.out.println("N:"+n); pw.println("retr "+n); do { try { str=br1.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"); }

Page 95: Network Programming Lab.ppt

public static void main(String args[]){

POPClient p=new POPClient();}

}

Page 96: Network Programming Lab.ppt
Page 97: Network Programming Lab.ppt

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.

Page 98: Network Programming Lab.ppt

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

Page 99: Network Programming Lab.ppt
Page 100: Network Programming Lab.ppt

FTP is used to: Promote sharing of files (computer

programs and/or data) Transfer data reliably, and efficiently

Page 101: Network Programming Lab.ppt

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()));

Page 102: Network Programming Lab.ppt

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 ((c=br.read())!=-1){

fos.write((char)c);fos.flush();

}System.out.println("File trasfer completed:\n");}catch (Exception e){System.out.println(e);}}}

Page 103: Network Programming Lab.ppt

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");

Page 104: Network Programming Lab.ppt

s = server.accept();System.out.println("Connection established:\n");br = new BufferedReader(new InputStreamReader(s.getInputStream()));pw = new PrintWriter(s.getOutputStream());filename = br.readLine();fis = new FileInputStream(filename);while ((c=fis.read())!=-1){ pw.print((char)c);pw.flush();}System.out.println(filename + " copied to destnation");s.close();}catch(Exception e){System.out.println(e);}}}

Page 105: Network Programming Lab.ppt

Output:

Page 106: Network Programming Lab.ppt
Page 107: Network Programming Lab.ppt

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.

Page 108: Network Programming Lab.ppt
Page 109: Network Programming Lab.ppt
Page 110: Network Programming Lab.ppt

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; public static String command = "";

Page 111: Network Programming Lab.ppt

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()); exit.addActionListener(new telnet()); help.addActionListener(new telnet());

Page 112: Network Programming Lab.ppt

//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) {}

Page 113: Network Programming Lab.ppt

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(!(s==null)) { System.out.println("in disconnecting...");

Page 114: Network Programming Lab.ppt

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().trim()));

Page 115: Network Programming Lab.ppt

br = new BufferedReader(new InputStreamReader(s.getInputStream())); pw = new PrintWriter(s.getOutputStream(),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;

Page 116: Network Programming Lab.ppt

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); } }}

 

Page 117: Network Programming Lab.ppt

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);

 Panel p3 = new Panel();p3.add(connect);p3.add(cancel);

Page 118: Network Programming Lab.ppt

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); }

Page 119: Network Programming Lab.ppt

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); }}

Page 120: Network Programming Lab.ppt

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); } }    

Page 121: Network Programming Lab.ppt
Page 122: Network Programming Lab.ppt
Page 123: Network Programming Lab.ppt
Page 124: Network Programming Lab.ppt

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.

Page 125: Network Programming Lab.ppt

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.

Page 126: Network Programming Lab.ppt

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.

Page 127: Network Programming Lab.ppt

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.

Page 128: Network Programming Lab.ppt

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.

Page 129: Network Programming Lab.ppt

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.

Page 130: Network Programming Lab.ppt

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.

Page 131: Network Programming Lab.ppt

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

informationFTP uses plain text channel

TFTP does not use logins

TFTP does not since it uses UDP

TFTP uses one connection (stop and wait)

Page 132: Network Programming Lab.ppt

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

Page 133: Network Programming Lab.ppt

SERVER SIDE PROGRAM:import java.io.*;import java.net.*;import java.lang.*;public class tftps{ public static void main(String args[]) throws Exception { DatagramSocket ds=new DatagramSocket(1500); byte s[]=new byte[1024]; DatagramPacket dp=new DatagramPacket(s,1024); ds.receive(dp); String data=new String(dp.getData(),0,dp.getLength()); int count=0; System.out.println("ENTER THE FILE NAME TO TRANFER:" +data); FileInputStream fs=new FileInputStream (data); while(fs.available()!=0) { if(fs.available()<1024) count=fs.available(););

Page 134: Network Programming Lab.ppt

else count=1024; s=new byte[count]; fs.read(sdp=new DatagramPacket(s,s.length,InetAddress.getLocalHost(),1501); ds.send(dp);}fs.close();s=new byte[3];s="***".getBytes(); ds.send(newDatagramPacket(s,s.length,InetAddress.getLocalHost(),1501));ds.close(); }}

Page 135: Network Programming Lab.ppt

CLIENT SIDE PROGRAM:

import java.io.*;import java.net.*;import java.lang.*;public class tftpc{

public static void main(String args[]) throws Exception{

DatagramSocket ds=new DatagramSocket(1501);BufferedReader input=newBufferedReader(new

InputStreamReader(System.in));System.out.println("ENTER THE FILE NAME TO SAVE:");String file=input.readLine();

FileOutputStream fos=new FileOutputStream(file);System.out.println("ENTER THE FILE NAME TO TRANFER:");file=input.readLine();byte s[]=new byte[file.length()];s=file.getBytes();

Page 136: Network Programming Lab.ppt

String data=null;ds.send(new

DatagramPacket(s,s.length,InetAddress.getLocalHost(),1500));while(true){

s=new byte[1024];DatagramPacket dp=new DatagramPacket(s,1024);

ds.receive(dp);data=new String(dp.getData(),0,dp.getLength());

if(data.equals("***"))break;fos.write(data.getBytes());

}fos.close();ds.close();

}}

Page 137: Network Programming Lab.ppt

Server side output:

Client side output:

Page 138: Network Programming Lab.ppt

Hyper Text Transfer protocol

Page 139: Network Programming Lab.ppt

Client/Server:

•A server is any thing that has some resource that can be shared.1.Compute servers2.Print server3.Disk servers4.Web servers

•A client is simply any other entity that wants to gain access to a particular server.

Page 140: Network Programming Lab.ppt

•static InetAddress getLocalHost() throws UnknownHostException

•static InetAddress getByName(String hostName) throws UnknownHostException

•static InetAddress[] getAllByName(String hostName) throws UnknownHostException

•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

This class is used to encapsulate numerical IP address and domain name for that address

Page 141: Network Programming Lab.ppt

import java.net.*;class InetAddressTest{ public static void main(String args[]) throws UnknownHostException{ InetAddress Address=InetAddress.getLocalHost(); System.out.println(Address); Address=InetAddress.getByName("yahoo.com"); System.out.println(Address); InetAddress sw[]=InetAddress.getAllByName("www.nba.com"); for(int i=0;i<sw.length;i++) System.out.println(sw[i]); }}

InetAddress example

Page 142: Network Programming Lab.ppt

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 ssoc=new ServerSocket(1111); System.out.println("Server waits for client:\n"); Socket so=ssoc.accept(); System.out.println("client connected to Server :\n");

BufferedReader br=new BufferedReader(new InputStreamReader(so.getInputStream()));

PrintWriter pw=new PrintWriter(so.getOutputStream(),true);

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

Page 143: Network Programming Lab.ppt

int ch;do{ ch=Integer.parseInt(br.readLine());

String file; byte line[]=null; File f; switch(ch)

{ case 1: System.out.println("1.head");

file=br.readLine(); f=new File(file); int index=file.lastIndexOf("."); String type=file.substring(index+1);

pw.println(type); long length=f.length(); pw.println(length);

break; case 2: System.out.println("2.post"); file=br.readLine();

System.out.println("message from client:\n");System.out.println(file);break;

Page 144: Network Programming Lab.ppt

case 3: System.out.println("3.get"); file=br.readLine(); FileInputStream fs=new FileInputStream(file); while(fs.available()!=0) {

if(fs.available()<1024) line=new byte[fs.available()];else line=new byte[1024]; fs.read(line); file=new String(line); pw.println(file);}pw.println("***");fs.close();break;

case 4: System.out.println("4.delete");file=br.readLine();f=new File(file);f.delete();break;

default: System.out.println("5.exit");System.exit(0);}

Page 145: Network Programming Lab.ppt

}while(ch<=4);

so.close();ssoc.close();

}}

Page 146: Network Programming Lab.ppt

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 soc=new Socket("localhost",1111); BufferedReader br=new BufferedReader(new InputStreamReader(soc.getInputStream()));

PrintWriter pw=new PrintWriter(soc.getOutputStream(),true);

BufferedReader in=new 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");

Page 147: Network Programming Lab.ppt

System.out.println("ENTER UR CHOICE:"); ch=Integer.parseInt(in.readLine()); byte line[]=null; String file; switch(ch) { case 1:pw.println("1");

file=in.readLine();pw.println(file);String type=br.readLine();String length=br.readLine();System.out.println("FILE:"+file+"\nTYPE:"+type+"\nLEN

GTH:"+length);break;

case 2: pw.println("2");

System.out.println("enter text to post"); file=in.readLine(); pw.println(file); System.out.println("text is posted at server");break;

Page 148: Network Programming Lab.ppt

case 3:pw.println("3"); System.out.println("enter file name to get"); file=in.readLine(); pw.println(file); System.out.println("enter file name to save:"); file=in.readLine(); FileOutputStream fs=new FileOutputStream(file); while(true) { String s=br.readLine(); if(s.equals("***")) break; int count=s.length(); if(count<1024) line=new byte[1024]; line=s.getBytes();

fs.write(line); }

fs.close(); System.out.println("\n file successfully tranfered:"); break;

Page 149: Network Programming Lab.ppt

case 4: pw.println("4"); System.out.println("enter the file to delete:"); file=in.readLine(); pw.println(file); System.out.println("given file deleted:"); break;

default: pw.println("5"); System.exit(0);}

} while(ch<=4); soc.close(); }}

Page 150: Network Programming Lab.ppt

Clint side Output window:

Page 151: Network Programming Lab.ppt