Professional Documents
Culture Documents
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());
}
} }}
Output:-
Socket Programming
Exception Handling
I/O and StreamClasses
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
try
{
code
}
CATCH BLOCK
catch (Exception ex)
{
<do something with ex>
}
catch
A method can catch an exception by providing an
exception handler for that type of exception.
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();
}
}
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;
}
}
catch(Exception e)
{
System.err.println(e);
}
pw.close();
br.close();
csoc.close();
ssoc.close();
}
}
Socket communication
Exception Handling
IO
Multi Threading
It
Print Writer:
public
PrintWriter(OutputStreamout,booleanautoFlush
)
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.
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.
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;
}
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);
}
}
}
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)
{
}
}
}
OUTPUT:
Output:
Server
1.
Re
qu
es
ve
Gi
s
re
tf
or
d
e
ns
po
fro
m
da
t
ab
as
to
e
cli
Data
base
at
a
nt
Client
Server
Server side program:
Server
Port
Port:
Port:
1111
1111
Establishing connections
Server
Accepting the connection
Socket csoc=ssoc.accept();
Client
In Server program:
BufferedReader fromc= new
BufferedReader(new
InputStreamReader(csoc.getInputStre
It reads input from socket object
csoc.getInputStream:
am()))
PrintStream toc=new
PrintStream(csoc.getOutputStre
am());
It writes stream of data to socket object
csoc.getOutputStream:
In client program:
BufferedReader froms=new
BufferedReader(new
InputStreamReader(soc.getInputStream()))
;
It reads input from socket object
BufferedReader fromkb=new
BufferedReader(new
InputStreamReader(System.in));
Takes the input from keyboard
Server
Connecting to data
base
Class.forName("sun.jdbc.odbc.JdbcOdbc
Driver");
Server
getCon
n
ection
()
Connection conn =
DriverManager.getConnection("jdbc:odbc:dns",userid",p
assword");
Server
interface
Statement
stmt=conn.createStatement();
Statement object is created for executing the SQL queries
Server
String query=fromkb.readLine();
Pose a query
Send to server
tos.println(query);
Client
Server
query=fromc.readLine();
Client
Metadata
if(query.equalsIgnoreCase("quit"))
break;
ResultSetMetaData rsmd=rs.getMetaDa
ResultSet rs=stmt.executeQuery(query
ce
a
f
r
Inte
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());
Server
toc.print(rset);
Client
query=froms.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
Server
Client
conn.close();
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());
}
}
}
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);
}
}
}
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);
}
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();
}
}
POP
SMTP
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);
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);
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);
}
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);
}
}
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("");
}
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);
}
}
}
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);
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()));
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();
}
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);
}
}
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");
}
FTP is
a standard network protocol used to
exchange and manipulate files over a
TCP/IP-based network, such as the
Internet.
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);
}
}
}
Output:
Program:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class telnet extends WindowAdapter implements
ActionListener,KeyListener {
//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) {}
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(Con
nectFrame.port.getText().trim()));
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;
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);
}
}
}
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");
connect.addActionListener(this);
cancel.addActionListener(this);
conFrame.setSize(250,200);
conFrame.add(p);
conFrame.setVisible(true);
conFrame.addWindowListener(this);
}
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.
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
else
count=1024;
s=new byte[count];
fs.read(s
dp=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();
}
}
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();
}
}
Client/Server:
A server is any thing that has some resource that can be shared
1.Compute servers
2.Print server
3.Disk servers
4.Web servers
InetAddress example
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]);
}
}
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;
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);
}
}
while(ch<=4);
so.close();
ssoc.close();
}
}
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;
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;
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();
}
}