Download import java.net.

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Socket Programming
Unit -2
Sockets – secure sockets – custom sockets – UDP datagrams – multicast sockets – URL classes –
Reading Data from the server – writing data – configuring the connection – Reading the header
– telnet application – Java Messaging services.
Socket




A socket is an endpoint between two way communications.
Java Socket programming is used for communication between the applications running on
different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
1. IP Address
An IP address is a 32-bit number that uniquely identifies a host (computer or other device, such as a
printer or router) on a TCP/IP network. IP addresses are normally expressed in dotted-decimal format,
with four numbers separated by periods, such as 192.168.123.132.
Like a car license plate, an IP address is a special serial number used for identification.
In the TCP/IP protocol, the unique identifier for a computer is called its IP address.
The web server is the program or machine that responds to that request, and delivers the content of the
page back to the user. This can be done because every computer or device that connects to the internet
has a uniquely identifying number, called an Internet Protocol address, or IP address
2. Port Number
Port numbers are part of the addressing information used to identify the senders and receivers
of messages.
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.
In both TCP and UDP, port numbers start at 0 and go up to 65535. Numbers in the lower ranges are
dedicated to common Internet protocols (like 21 for FTP and 80 for HTTP).
Just as a business telephone switchboard can use a main phone number and assign each employee an
extension number (like x100, x101, etc.), so a computer has a main address and a set of port numbers
to handle incoming and outgoing connections.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be
used to create a socket.
Important methods
Method
Description
1) public InputStream getInputStream()
returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.
3) public synchronized void close()
closes this socket
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method
Description
1) public Socket accept()
returns the socket and establish a connection between server and
client.
2) public synchronized void
close()
closes the server socket.
Example of Java Socket Programming
Let's see a simple of java socket programming in which client sends a text and server receives it.
File: MyServer.java
1.
2.
3.
4.
5.
6.
7.
8.
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
File: MyClient.java
1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
To execute this program open two command prompts and execute each program at each command
prompt as displayed in the below figure.After running the client application, a message will be
displayed on the server console.
Example of Java Socket Programming (Read-Write both side)
In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes on.
File: MyServer.java
1. import java.net.*;
2. import java.io.*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=ss.accept();
7. DataInputStream din=new DataInputStream(s.getInputStream());
8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
9. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
10.
11. String str="",str2="";
12. while(!str.equals("stop")){
13. str=din.readUTF();
14. System.out.println("client says: "+str);
15. str2=br.readLine();
16. dout.writeUTF(str2);
17. dout.flush();
18. }
19. din.close();
20. s.close();
21. ss.close();
22. }}
File: MyClient.java
1. import java.net.*;
2. import java.io.*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream(s.getInputStream());
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9. String str="",str2="";
10. while(!str.equals("stop")){
11. str=br.readLine();
12. dout.writeUTF(str);
13. dout.flush();
14. str2=din.readUTF();
15. System.out.println("Server says: "+str2);
16. }
17.
18. dout.close();
19. s.close();
20. }}
Secure Sockets
What Is SSL?
SSL (Secure Sockets Layer) is a standard security technology for establishing an encrypted link
between a server and a client—typically a web server (website) and a browser, or a mail server and a
mail client.
What is an SSL Certificate and How Does it Work?
SSL Certificates have a key pair: a public and a private key. These keys work together to establish an
encrypted connection. The certificate also contains what is called the “subject,” which is the identity of
the certificate/website owner.
To get a certificate, you must create a Certificate Signing Request (CSR) on your server. This process
creates a private key and public key on your server. The CSR data file that you send to the SSL
Certificate issuer (called a Certificate Authority or CA) contains the public key. The CA uses the CSR
data file to create a data structure to match your private key without compromising the key itself. The
CA never sees the private key.
Once you receive the SSL Certificate, you install it on your server. You also install an intermediate
certificate that establishes the credibility of your SSL Certificate by tying it to your CA’s root
certificate. The instructions for installing and testing your certificate will be different depending on
your server.
How Does the SSL Certificate Create a Secure Connection?
When a browser attempts to access a website that is secured by SSL, the browser and the web server
establish an SSL connection using a process called an “SSL Handshake” (see diagram below). Note
that the SSL Handshake is invisible to the user and happens instantaneously.
Essentially, three keys are used to set up the SSL connection: the public, private, and session keys.
Anything encrypted with the public key can only be decrypted with the private key, and vice versa.
Because encrypting and decrypting with private and public key takes a lot of processing power, they
are only used during the SSL Handshake to create a symmetric session key. After the secure
connection is made, the session key is used to encrypt all transmitted data.
1. Browser connects to a web server (website) secured with SSL (https). Browser requests that
the server identify itself.
2. Server sends a copy of its SSL Certificate, including the server’s public key.
3. Browser checks the certificate root against a list of trusted CAs and that the certificate is
unexpired, unrevoked, and that its common name is valid for the website that it is connecting
to. If the browser trusts the certificate, it creates, encrypts, and sends back a symmetric session
key using the server’s public key.
4. Server decrypts the symmetric session key using its private key and sends back an
acknowledgement encrypted with the session key to start the encrypted session.
5. Server and Browser now encrypt all transmitted data with the session key.
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points
to a resource on the World Wide Web. For example:
http://www.javatpoint.com/java-tutorial
A URL contains many information:
1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.javatpoint.com is the server name.
3. Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ ,
80 is the port number. If port number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.
Commonly used methods of Java URL class
The java.net.URL class provides many methods. The important methods of URL class are given
below.
Method
public String getProtocol()
public String getHost()
public String getPort()
public String getFile()
public URLConnection
openConnection()
Description
it returns the protocol of the URL.
it returns the host name of the URL.
it returns the Port Number of the URL.
it returns the file name of the URL.
it returns the instance of URLConnection i.e. associated with
this URL.
Example of Java URL class
1. //URLDemo.java
2. import java.io.*;
3. import java.net.*;
4. public class URLDemo{
5. public static void main(String[] args){
6. try{
7. URL url=new URL("http://www.javatpoint.com/java-tutorial");
8.
9. System.out.println("Protocol: "+url.getProtocol());
10. System.out.println("Host Name: "+url.getHost());
11. System.out.println("Port Number: "+url.getPort());
12. System.out.println("File Name: "+url.getFile());
13.
14. }catch(Exception e){System.out.println(e);}
15. }
16. }
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
Java DatagramSocket and DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Java DatagramSocket class
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram
packets.
A datagram is basically information but there is no guarantee of its content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class



DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it
with the given Port Number.
DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address.
Java DatagramPacket class
Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may
arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class


DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is
used to receive the packets.
DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a
datagram packet. This constructor is used to send the packets.
Example of Sending DatagramPacket by DatagramSocket
//DSender.java
1. import java.net.*;
2. public class DSender{
3. public static void main(String[] args) throws Exception {
4.
DatagramSocket ds = new DatagramSocket();
5.
String str = "Welcome java";
6.
InetAddress ip = InetAddress.getByName("127.0.0.1");
7.
8.
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
9.
ds.send(dp);
10. ds.close();
11. }
12. }
Example of Receiving DatagramPacket by DatagramSocket
//DReceiver.java
1. import java.net.*;
2. public class DReceiver{
3. public static void main(String[] args) throws Exception {
4.
DatagramSocket ds = new DatagramSocket(3000);
5.
byte[] buf = new byte[1024];
6.
DatagramPacket dp = new DatagramPacket(buf, 1024);
7.
ds.receive(dp);
8.
String str = new String(dp.getData(), 0, dp.getLength());
9.
System.out.println(str);
10. ds.close();
11. }
12. }
Multicast sockets
In this Explain how to use MulticastSocket in Java, in order to enable a server to easily
send information to multiple clients, which are all connected to the same port and
address. We will describe the whole process, by creating both the server and
the client, and guide you through the main concepts that need to be understood to
create this type of applications.
1. MulticastSocket Server
We are going to use a DatagramSocket, to enable the server to send packets of
information to the client/clients. A datagram, by definition, is “an independent, selfcontained message sent over the network whose arrival, arrival time, and content are
not guaranteed”. Essentially, we are opening a DatagramSocket in order to send
DatagramPacket messages to the client. We are using the datagram classes (instead of
standard sockets) because they allow us to broadcast information to multiple clients,
that are all connected to a MulticastSocket.
MulticastSocketServer.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MulticastSocketServer {
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws UnknownHostException, InterruptedException
{
// Get the address that we are going to connect to.
InetAddress addr = InetAddress.getByName(INET_ADDR);
// Open a new DatagramSocket, which will be used to send the data.
try (DatagramSocket serverSocket = new DatagramSocket()) {
for (int i = 0; i < 5; i++) {
String msg = "Sent message no " + i;
// Create a packet that will contain the data
// (in the form of bytes) and send it.
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, addr, PORT);
serverSocket.send(msgPacket);
System.out.println("Server sent packet with msg: " + msg);
Thread.sleep(500);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
One thing that we need to take into consideration here, is that there are specific addresses that allow us
to use a MulticastSocket are limited, specifically in the range of 224.0.0.0 to 239.255.255.255. Some
of them are reserved, like 224.0.0.0. The address that we are using, 224.0.0.3, can be used safely.
2. Multicast Socket Client
Regarding the client, we are going to move a little bit differently. We are going to create a client class,
that will accept incoming messages from the server, and then we are going to duplicate this class. The
point here is that by using the same code, we can connect to the server seamlessly, while having as
many clients as we like.
MulticastSocketClient.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
public class MulticastSocketClient {
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws UnknownHostException {
/ Get the address that we are going to connect to.
InetAddress address = InetAddress.getByName(INET_ADDR);
// Create a buffer of bytes, which will be used to store
// the incoming bytes containing the information from the server.
// Since the message is small here, 256 bytes should be enough.
byte[] buf = new byte[256];
// Create a new Multicast socket (that will allow other sockets/programs
// to join it as well.
try (MulticastSocket clientSocket = new MulticastSocket(PORT))
{
//Joint the Multicast group.
clientSocket.joinGroup(address);
while (true) {
// Receive the information and print it.
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket)
String msg = new String(buf, 0, buf.length);
System.out.println("Socket 1 received msg: " + msg);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
First, we start the client, which will keep waiting for incoming packets of information. As soon as we
start the server, it will send the information packets and the client will receive them and print the
information on the screen.
Server Output
Server sent packet with msg: Sent message no 0
Server sent packet with msg: Sent message no 1
Server sent packet with msg: Sent message no 2
Server sent packet with msg: Sent message no 3
Server sent packet with msg: Sent message no 4
Client Output
Socket 1 received msg: Sent message no 0
Socket 1 received msg: Sent message no 1
Socket 1 received msg: Sent message no 2
Socket 1 received msg: Sent message no 3
Socket 1 received msg: Sent message no 4
Telnet Applications
// 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
import
import
import
import
java.net.*;
java.io.*;
java.lang.*;
java.io.*;
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 (Java Message Service)
Java Message Service is an API which supports the formal communication called as messaging
between computers on a network. It provides a common interface for standard message protocols and
message services in support to the Java programs. It provides facility to create, send and read
messages
JMS (Java Message Service) is an API that provides the facility to create, send and read messages. It
provides loosely coupled, reliable and asynchronous communication.JMS is also known as a
messaging service.
Understanding Messaging
Messaging is a technique to communicate applications or software components.JMS is mainly used to
send and receive message from one application to another.
Requirement of JMS
Generally, user sends message to application. But, if we want to send message from one application to
another, we need to use JMS API.
Consider a scenario, one application A is running in INDIA and another application B is running in
USA. To send message from A application to B, we need to use JMS.
Advantage of JMS
1) Asynchronous: To receive the message, client is not required to send request. Message will arrive
automatically to the client.
2) Reliable: It provides assurance that message is delivered.
Messaging Domains
There are two types of messaging domains in JMS.
1. Point-to-Point Messaging Domain
2. Publisher/Subscriber Messaging Domain
1) Point-to-Point (PTP) Messaging Domain
In PTP model, one message is delivered to one receiver only. Here, Queue is used as a message
oriented middleware (MOM).
The Queue is responsible to hold the message until receiver is ready.
In PTP model, there is no timing dependency between sender and receiver.
2) Publisher/Subscriber (Pub/Sub) Messaging Domain
In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting. Here,
Topic is used as a message oriented middleware that is responsible to hold and deliver messages.
In PTP model, there is timing dependency between publisher and subscriber.
JMS Programming Model
JMS Queue Example
To develop JMS queue example, you need to install any application server. Here, we are using
glassfish3 server where we are creating two JNDI.
1. Create connection factory named myQueueConnectionFactory
2. Create destination resource named myQueue
After creating JNDI, create server and receiver application. You need to run server and receiver in
different console. Here, we are using eclipse IDE, it is opened in different console by default.
1) Create connection factory and destination resource
Open server admin console by the URL http://localhost:4848
Login with the username and password.
Click on the JMS Resource -> Connection Factories -> New, now write the pool name and select the
Resource Type as QueueConnectionFactory then click on ok button.
2) Create sender and receiver application
Let's see the Sender and Receiver code. Note that Receiver is attached with listener which will
be invoked when user sends message.
File: MySender.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.naming.*;
import javax.jms.*;
public class MySender {
public static void main(String[] args) {
try
{ //Create and start connection
InitialContext ctx=new InitialContext();
QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");
QueueConnection con=f.createQueueConnection();
con.start();
//2) create queue session
QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
//3) get the Queue object
Queue t=(Queue)ctx.lookup("myQueue");
//4)create QueueSender object
QueueSender sender=ses.createSender(t);
//5) create TextMessage object
TextMessage msg=ses.createTextMessage();
//6) write message
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("Enter Msg, end to terminate:");
String s=b.readLine();
if (s.equals("end"))
break;
msg.setText(s);
//7) send message
sender.send(msg);
System.out.println("Message successfully sent.");
}
//8) connection close
con.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyReceiver.java
import javax.jms.*;
import javax.naming.InitialContext;
public class MyReceiver {
public static void main(String[] args) {
try{
//1) Create and start connection
InitialContext ctx=new InitialContext();
QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");
QueueConnection con=f.createQueueConnection();
con.start();
//2) create Queue session
QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
//3) get the Queue object
Queue t=(Queue)ctx.lookup("myQueue");
//4)create QueueReceiver
QueueReceiver receiver=ses.createReceiver(t);
//5) create listener object
MyListener listener=new MyListener();
//6) register the listener object with receiver
receiver.setMessageListener(listener);
System.out.println("Receiver1 is ready, waiting for messages...");
System.out.println("press Ctrl+c to shutdown...");
while(true){
Thread.sleep(1000);
}
}catch(Exception e){System.out.println(e);}
}
}
File: MyListener.java
import javax.jms.*;
public class MyListener implements MessageListener {
public void onMessage(Message m) {
try{
TextMessage msg=(TextMessage)m;
System.out.println("following message is received:"+msg.getText());
}catch(JMSException e){System.out.println(e);}
}
}
Run the Receiver class first then Sender class.
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.
File: MySender.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.naming.*;
import javax.jms.*;
public class MySender {
public static void main(String[] args) {
try
{ //Create and start connection
InitialContext ctx=new InitialContext();
TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFactory");
TopicConnection con=f.createTopicConnection();
con.start();
//2) create queue session
TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
//3) get the Topic object
Topic t=(Topic)ctx.lookup("myTopic");
//4)create TopicPublisher object
TopicPublisher publisher=ses.createPublisher(t);
//5) create TextMessage object
TextMessage msg=ses.createTextMessage();
//6) write message
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("Enter Msg, end to terminate:");
String s=b.readLine();
if (s.equals("end"))
break;
msg.setText(s);
//7) send message
publisher.publish(msg);
System.out.println("Message successfully sent.");
}
//8) connection close
con.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyReceiver.java
import javax.jms.*;
import javax.naming.InitialContext;
public class MyReceiver {
public static void main(String[] args) {
try {
//1) Create and start connection
InitialContext ctx=new InitialContext();
TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFactory");
TopicConnection con=f.createTopicConnection();
con.start();
//2) create topic session
TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
//3) get the Topic object
Topic t=(Topic)ctx.lookup("myTopic");
//4)create TopicSubscriber
TopicSubscriber receiver=ses.createSubscriber(t);
//5) create listener object
MyListener listener=new MyListener();
//6) register the listener object with subscriber
receiver.setMessageListener(listener);
System.out.println("Subscriber1 is ready, waiting for messages...");
System.out.println("press Ctrl+c to shutdown...");
while(true){
Thread.sleep(1000);
}
}catch(Exception e){System.out.println(e);}
}
}
File: MyListener.java
import javax.jms.*;
public class MyListener implements MessageListener {
public void onMessage(Message m) {
try{
TextMessage msg=(TextMessage)m;
System.out.println("following message is received:"+msg.getText());
}catch(JMSException e){System.out.println(e);}
} }