Vous êtes sur la page 1sur 21

An

U –I Book
cittivity

im
p
try
S
D
d
d
u
op
au
o
au
co
{b
talice
k rtts
t.t.O
fwu
le
u
cja la
ta
iss
r(); =
tp
e
vti
xh
sn
u
U
..inw
asce
tSv
c();eT pF
oeo
M
tr
.t.*
*y;iC
e"S
ti(o
ad
H o;m
mlik
c eda n
e
neell){oSS
(tu
oitn "{(S
ye
tr
lov
t= ain
ce
n
srte
go
lh
rw
[]saa
".o);D
rg
t"ta s
,6O)6{tp
6u
1.

6);utStream(s.getOutputStream());
Writeasimplejava

Ce
Rlief:nh
tttpprs
o://
grwaw
m
socket programming in which client sends a text and server receives it.
w.javatpoint.com/socket-program
ming
}c.o
s c lo
tc hc
s o
(E e m ut.println(e);}

Server program
im
p u
try
S e
o p
r{b
cn oliIe
vte
k rrttS
cn cja
s la
stao
=vcssak
ti c..ie
str
s
o
n.v
M
a
.t.*
teac
o
s*ys
;d
ciS=;p
enrit(s
m va)=
e ;/ienn
w /rS{es
(S rtra
esw ib
vDn
eg []h
lirS oIan
crp
gu
kesctt(){S
6n
6n
6ea
6m
);ti(s
D
S a.s
tr
}csy
s ac ita
tc log
hm sp
(E e.uo
xu
tS
();ct.ep
e
ptirionm tle
n
d
n
e(){"m Syesste
e ta
m g a
.e
o=
s
ta
ut."+
e
ps
s
ritr
o tr
ntl);n(e);}
ec on
.getInputStream()); str=(String)dis.readUTF();

Output

2.Program to Build secure network


applications with SSL and the JSSE API
https://www.javaworld.com/article/2075291/learn-java/build-secure-network-
applications-with-ssl-and-the-jsse-api.html

Server program
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
public
class EchoServer
{
public
static
void
main(String [] arstring)
{
try
{
SSLServerSocketFactory sslserversocketfactory =
(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket =
(SSLServerSocket)sslserversocketfactory.createServerSocket(9999);
SSLSocket sslsocket = (SSLSocket)sslserversocket.accept();
InputStream inputstream = sslsocket.getInputStream();
InputStreamReader inputstreamreader = new
InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String string = null;
while ((string = bufferedreader.readLine()) != null)
{
System.out.println(string);
System.out.flush();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}

Client program

import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public
class EchoClient
{
public
static
void
main(String [] arstring)
{
try
{
SSLSocketFactory sslsocketfactory =
(SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket sslsocket =
(SSLSocket)sslsocketfactory.createSocket("localhost", 9999);
InputStream inputstream = System.in;
InputStreamReader inputstreamreader = new
InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
OutputStream outputstream = sslsocket.getOutputStream();
OutputStreamWriter outputstreamwriter = new
OutputStreamWriter(outputstream);
BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
String string = null;
while ((string = bufferedreader.readLine()) != null)
{
bufferedwriter.write(string + '\n');
bufferedwriter.flush();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}
2.2 CUSTOM SOCKET Ref: https://www.daniweb.com/programming/software-
development/threads/422352/simple-client-server-sockets-example-problem
2.3 Socket program to calculate factorial of a no

// client.java

import java.net.*;

import java.io.*;

public class client

public static void main(String args[])

try

Socket s = new Socket("localhost",2222);

InputStream is=s.getInputStream();

InputStreamReader isr= new InputStreamReader(is);

BufferedReader br=new BufferedReader(isr);


OutputStream os=s.getOutputStream();

PrintWriter pw= new PrintWriter(os,true);

int msg=6;

pw.println(msg);

msg=br.read();

System.out.println("factorial="+msg);

s.close();

catch (Exception e)

e.printStackTrace();

//server.java

import java.net.*;

import java.io.*;

public class server

public static void main(String args[])

try

{
ServerSocket ss =new ServerSocket(2222);

System.out.println("Server is started");

while(true)

Socket s=ss.accept();

System.out.print("Connection request Received");

InputStream is=s.getInputStream();

InputStreamReader isr= new InputStreamReader(is);

BufferedReader br=new BufferedReader(isr);

OutputStream os=s.getOutputStream();

PrintWriter pw= new PrintWriter(os,true);

int no=br.read();

int fact=1,i=0;

while(no>i)

fact=fact*no;

no--;

pw.println(fact);

s.close();

catch(Exception e)
{

e.printStackTrace();

3.1 TCP PROGRAM REF: https://itiansweb.blogspot.com/2016/12/implementation-of-client-server.html

Implementation of Client Server


communication model
Practical 1A: A client server based program using TCP to find if the number entered is prime.
Code:
1. tcpServerPrime.java:
import java.net.*;
import java.io.*;
class tcpServerPrime
{
public static void main(String args[])
{
try
{
ServerSocket ss = new ServerSocket(8001);
System.out.println("Server Started...............");
Socket s = ss.accept();
DataInputStream in = new DataInputStream(s.getInputStream());
int x= in.readInt();
DataOutputStream otc = new DataOutputStream(s.getOutputStream());
int y = x/2;
if(x ==1 || x ==2 || x ==3)
{
otc.writeUTF(x + "is Prime");
System.exit(0);
}
for(int i=2; i<=y; i++)
{
if(x%i != 0)
{
otc.writeUTF(x + " is Prime");
}
else
{
otc.writeUTF(x + " is not Prime");
}
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}

2. tcpClientPrime.java:
import java.net.*;
import java.io.*;
class tcpClientPrime
{
public static void main(String args[])
{
try
{
Socket cs = new Socket("192.168.1.254",8001);
BufferedReader infu = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number : ");
int a = Integer.parseInt(infu.readLine());
DataOutputStream out = new DataOutputStream(cs.getOutputStream());
out.writeInt(a);
DataInputStream in = new DataInputStream(cs.getInputStream());
System.out.println(in.readUTF());
cs.close();
}
catch(Exception e)
{
System.out.println(e.toString());

}}}

3 .2 UDP PROGRAM REF; https://itiansweb.blogspot.com/2016/12/a-client-server-based-program-


using-udp.html
A client server based program using UDP to
find if the number entered is even or odd.
1. udpServerEO.java:
import java.io.*;
import java.net.*;
public class udpServerEO
{
public static void main(String args[])
{
try
{
DatagramSocket ds = new DatagramSocket(2000);
byte b[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(b,b.length);
ds.receive(dp);
String str = new String(dp.getData(),0,dp.getLength());
System.out.println(str);
int a= Integer.parseInt(str);
String s= new String();
if (a%2 == 0)
s = "Number is even";
else
s = "Number is odd";
byte b1[] = new byte[1024];
b1 = s.getBytes();
DatagramPacket dp1 = new
DatagramPacket(b1,b1.length,InetAddress.getLocalHost(),1000);
ds.send(dp1);
}
catch(Exception e)

{
e.printStackTrace();
}
}
}

2. udpClientEO.java :
import java.io.*;
import java.net.*;
public class udpClientEO
{
public static void main(String args[])
{
try
{
DatagramSocket ds = new DatagramSocket(1000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a number : ");
String num = br.readLine();
byte b[] = new byte[1024];
b=num.getBytes();
DatagramPacket dp = new
DatagramPacket(b,b.length,InetAddress.getLocalHost(),2000);
ds.send(dp);
byte b1[] = new byte[1024];
DatagramPacket dp1 = new DatagramPacket(b1,b1.length);
ds.receive(dp1);
String str = new String(dp1.getData(),0,dp1.getLength());
System.out.println(str);
}
catch(Exception e)
{
e.printStackTrace();
}}}

The Following source code is an simple example for broadcasting. It broadcast date

andtime to its multiple clients. ( from java 1.1 developers handbook )

4.1 Server Program

import java.net.*;
import java.io.*;
import java.util.*;
public class BroadcastServer{
public static final int PORT = 1200;
public static void main(String args[]) throws Exception{
MulticastSocket socket;
DatagramPacket packet;
InetAddress address;

address = InetAddress.getByName();
socket = new MulticastSocket();
// join a Multicast group and send the group salutations
socket.joinGroup(address);
byte[] data = null;
for(;;){

Thread.sleep(1000);
System.out.println("Sending ");
String str = (new Date()).toString();
data = str.getBytes();

packet = new DatagramPacket(data,str.length(),address,PORT);

// Sends the packet

socket.send(packet);
} // for

} // main

} // class BroadcastServer
4.1

//URLDemo.java

import java.io.*;

import java.net.*;

public class URLDemo{

public static void main(String[] args){

try{

URL url=new URL("http://www.javatpoint.com/java-tutorial");

System.out.println("Protocol: "+url.getProtocol());

System.out.println("Host Name: "+url.getHost());

System.out.println("Port Number: "+url.getPort());

System.out.println("File Name: "+url.getFile());

}catch(Exception e){System.out.println(e);}

4.2 Client program

import java.net.*;
import java.io.*;
public class BroadcastClient{
public static final int PORT = 1200;
public static void main(String args[]) throws Exception{

MulticastSocket socket;
DatagramPacket packet;
InetAddress address;

address = InetAddress.getByName(args[0]);
socket = new MulticastSocket(BroadcastServer.PORT);
//join a Multicast group and send the group salutations
socket.joinGroup(address);
byte[] data = null;
packet = new DatagramPacket(data,data.length);
for(;;){
// receive the packets

socket.receive(packet);
String str = new String(packet.getData());
System.out.println(" Time signal recieved from"+
packet.getAddress() + " Time is : " +str);
} // for
} // main
} // class Broadcast
url reading and writing
// TextBasedSearchEngine.java:
import java.io.*;
import java.net.*;
public class TextBasedSearchEngine {
private String searchEngine;
public TextBasedSearchEngine(String searchEngine) {
this.searchEngine = searchEngine;
}
public void doSearch(String queryString) {
try {
// open a url connection
URL url = new URL(searchEngine);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
// write the query string to the search engine
PrintStream ps = new PrintStream(connection.getOutputStream());
ps.println(queryString);
ps.close();
// read the result
DataInputStream input =
new DataInputStream(connection.getInputStream());
String inputLine = null;
while((inputLine = input.readLine())!= null) {
System.out.println(inputLine);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
QueryStringFormatter formatter =
new QueryStringFormatter(“http://search.yahoo.com/search”);
formatter.addQuery(“newwindow”,“1");
formatter.addQuery(“q”,“Xingchen Chu & Rajkumar Buyya”);
// search it via yahoo
TextBasedSearchEngine search =
new TextBasedSearchEngine(formatter.getEngine());
search.doSearch(formatter.getQueryString());
}
}
4.2 Writing and Reading Data via URLConnection
// TextBasedSearchEngine.java:
import java.io.*;
import java.net.*;
public class TextBasedSearchEngine {
private String searchEngine;
public TextBasedSearchEngine(String searchEngine) {
this.searchEngine = searchEngine;
}
public void doSearch(String queryString) {
try {
// open a url connection
URL url = new URL(searchEngine);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
// write the query string to the search engine
PrintStream ps = new PrintStream(connection.getOutputStream());
ps.println(queryString);
ps.close();
// read the result
DataInputStream input =
new DataInputStream(connection.getInputStream());
String inputLine = null;
while((inputLine = input.readLine())!= null) {
System.out.println(inputLine);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
QueryStringFormatter formatter =
new QueryStringFormatter(“http://search.yahoo.com/search”);
formatter.addQuery(“newwindow”,“1");
formatter.addQuery(“q”,“Xingchen Chu & Rajkumar Buyya”);
// search it via yahoo
TextBasedSearchEngine search =
new TextBasedSearchEngine(formatter.getEngine());
search.doSearch(formatter.getQueryString());
}
}
Output
<!doctype html public “-//W3C/DTD HTML 4.01//EN” “http://www.w3.org/TR/
html4/strict.dtd”>
<html>
<head>
...
...
</html>

Code for Program of telnet server - client in Java

// Telnet Client

import java.net.*;
import java.io.*;

class TelnetClient
{
publicstaticvoid main(String args[]) throws Exception
{
Socket soc=new Socket("127.0.0.1",5217);
String LoginName;
String Password;
String Command;

DataInputStream din=new DataInputStream(soc.getInputStream());


DataOutputStream dout=new DataOutputStream(soc.getOutputStream());
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));

System.out.println("Welcome to Telnet Client");


System.out.println("Your Credential Please...");
System.out.print("Login Name :");

LoginName=br.readLine();

System.out.print("Password :");
Password=br.readLine();

dout.writeUTF(LoginName);
dout.writeUTF(Password);

if (din.readUTF().equals("ALLOWED"))
{
do
{
System.out.print("< Telnet Prompt >");
Command=br.readLine();
dout.writeUTF(Command);
if(!Command.equals("quit"))
{
System.out.println(din.readUTF());
}
}while(!Command.equals("quit"));
}
soc.close();
}
}

// Telnet server

import java.net.*;
import java.io.*;
import java.lang.*;
import java.io.*;
import java.util.*;

class TelnetServer
{
publicstaticvoid main(String args[]) throws Exception
{
ServerSocket Soc=new ServerSocket(5217);
while(true)
{
Socket CSoc=Soc.accept();
AcceptTelnetClient ob=new AcceptTelnetClient(CSoc);
}
}
}

class AcceptTelnetClient extends Thread


{
Socket ClientSocket;
DataInputStream din;
DataOutputStream dout;
String LoginName;
String Password;

AcceptTelnetClient(Socket CSoc) throws Exception


{
ClientSocket=CSoc;
System.out.println("Client Connected ...");
DataInputStream din=new
DataInputStream(ClientSocket.getInputStream());
DataOutputStream dout=new
DataOutputStream(ClientSocket.getOutputStream());

System.out.println("Waiting for UserName And Password");

LoginName=din.readUTF();
Password=din.readUTF();

start();
}
publicvoid run()
{
try
{
DataInputStream din=new
DataInputStream(ClientSocket.getInputStream());
DataOutputStream dout=new
DataOutputStream(ClientSocket.getOutputStream());

BufferedReader brFin=new BufferedReader(new


FileReader("Passwords.txt"));

String LoginInfo=new String("");


boolean allow=false;

while((LoginInfo=brFin.readLine())!=null)
{
StringTokenizer st=new StringTokenizer(LoginInfo);
if(LoginName.equals(st.nextToken()) &&
Password.equals(st.nextToken()))
{
dout.writeUTF("ALLOWED");
allow=true;
break;
}
}

brFin.close();

if (allow==false)
{
dout.writeUTF("NOT_ALLOWED");
}

while(allow)
{
String strCommand;
strCommand=din.readUTF();
if(strCommand.equals("quit"))
{
allow=false;
}
else
{
Runtime rt=Runtime.getRuntime();

Process p=rt.exec("TelnetServer.bat " + strCommand);

String stdout=new String("");


String st;
DataInputStream dstdin=new
DataInputStream(p.getInputStream());
while((st=dstdin.readLine())!=null)
{
stdout=stdout +st + "\n";
}
dstdin.close();
dout.writeUTF(stdout);
}
}
ClientSocket.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

JMS Topic Example

It is same as JMS Queue, but you need to change Queue to Topic, Sender to Publisher and
Receiver to Subscriber.

You need to create 2 JNDI named myTopicConnectionFactory and myTopic.

MySender.java

1. import java.io.BufferedReader;
2. import java.io.InputStreamReader;
3. import javax.naming.*;
4. import javax.jms.*;
5.
6. public class MySender {
7. public static void main(String[] args) {
8. try
9. { //Create and start connection
10. InitialContext ctx=new InitialContext();
11. TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConn
ectionFactory");
12. TopicConnection con=f.createTopicConnection();
13. con.start();
14. //2) create queue session
15. TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLED
GE);
16. //3) get the Topic object
17. Topic t=(Topic)ctx.lookup("myTopic");
18. //4)create TopicPublisher object
19. TopicPublisher publisher=ses.createPublisher(t);
20. //5) create TextMessage object
21. TextMessage msg=ses.createTextMessage();
22.
23. //6) write message
24. BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
25. while(true)
26. {
27. System.out.println("Enter Msg, end to terminate:");
28. String s=b.readLine();
29. if (s.equals("end"))
30. break;
31. msg.setText(s);
32. //7) send message
33. publisher.publish(msg);
34. System.out.println("Message successfully sent.");
35. }
36. //8) connection close
37. con.close();
38. }catch(Exception e){System.out.println(e);}
39. }
40. }

MyReceiver.java

1. import javax.jms.*;
2. import javax.naming.InitialContext;
3.
4. public class MyReceiver {
5. public static void main(String[] args) {
6. try {
7. //1) Create and start connection
8. InitialContext ctx=new InitialContext();
9. TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConn
ectionFactory");
10. TopicConnection con=f.createTopicConnection();
11. con.start();
12. //2) create topic session
13. TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLED
GE);
14. //3) get the Topic object
15. Topic t=(Topic)ctx.lookup("myTopic");
16. //4)create TopicSubscriber
17. TopicSubscriber receiver=ses.createSubscriber(t);
18.
19. //5) create listener object
20. MyListener listener=new MyListener();
21.
22. //6) register the listener object with subscriber
23. receiver.setMessageListener(listener);
24.
25. System.out.println("Subscriber1 is ready, waiting for messages...");
26. System.out.println("press Ctrl+c to shutdown...");
27. while(true){
28. Thread.sleep(1000);
29. }
30. }catch(Exception e){System.out.println(e);}
31. }
32.
33. }

MyListener.java

1. import javax.jms.*;
2. public class MyListener implements MessageListener {
3.
4. public void onMessage(Message m) {
5. try{
6. TextMessage msg=(TextMessage)m;
7.
8. System.out.println("following message is received:"+msg.getText());
9. }catch(JMSException e){System.out.println(e);}
10. }
11. }