Advanced Socket Programming Socket Timeouts Interruptible Sockets Half-Close Internet Address Java Mail Messaging System
Advanced Socket Programming Socket Timeouts Interruptible Sockets Half-Close Internet Address Java Mail Messaging System
1
Socket Timeouts
Problem:If the host is unreachable,
then your application waits for a long
time or read methods will block until
data are available so.
Java offers Socket.setSoTimeout to
control how long you are willing to wait
for a read to complete.
Decide what time out value is
reasonable for your application.
2
Then call the setSoTimeout method to set a
time out value(in milliseconds)
Socket s=new Socket(….);
S.setSoTimeout(10000);//time out after 10
seconds.
If the time out value has been set for a
socket,then all subsequent read and write
operations throw a SocketTimeoutException
when the time out has been reached before the
operation has completed its work.
3
Case-2: The constructor Socket(String host,int port)
can block indefinitely until an initial connection to the
host is established.
Solution: First construct an unconnected socket and
then connecting it with a timeout.
Socket s=new Socket();
s.connect(new InetSocketAddress(host,port),timeout);
4
Interruptible sockets
Gives user an option to simply cancel
a socket connection that does not
appear to produce results.
For ex in a client server application if
the server pretends to be busy and
does send any reply to the
client..client can click cancel button to
terminate the connection.
5
To interrupt a socket operation ,SocketChannel
is used,a feature of the java.nio package.
SocketChannel
channel=SocketChannel.open(new
InetSocketAddress(host,port));
Whenever a thread is interrupted during an
open ,read or write operation ,the operation
does not block but is terminated with an
exception
6
Half-close
When a client program sends a request to the
server, server needs to be able to determine
when the end of request occurs.
This can be accomplished by closing the output
stream of a socket, thereby indicating to the
server the end of the request data, but keeping
the input stream open to read the response
coming from server.
So if you want to shut down only half of the
connection, either input or output -the
shutdownInput() and shutdownOutput method
7
Let you close only half of the
connection.
This down not close the socket
8
Internet Address
InetAddress class ->used to convert between host
names and internet addresses.
InetAddress
address=InetAddress.getByName(“hostname”);
Returns an Inetaddress object that encapsulates the
sequence of four bytes
like 132.163.4.104.
To access the bytes use getAddress method
Byte[] addressbytes=address.getAddress();
9
Java Mail Messaging System
10
E-Mail Messaging System
Java e-mail messaging system is composed of mail
clients and mail servers.
An e-mail client is a GUI based application installed on
user’s machine. The most popular are netscape
communication and MS outlook.
An e-mail server is responsible for routing messages to
their destination and also storing messages until the
user receives them:
SMTP defines the process for sending e-mail in a reliable
and efficient manner.
POP3 defines mechanism for retrieving messages from a
mail server. The POP3 protocol identifies the user and
the password and retrieves only those messages for the
given user.
11
Process of E-Mail Transmission
messages
12
Anatomy of an E-mail Message
An e-mail message is composed of two major sections. Headers
containing a set of attributes and body( content).
Message
Header Sender,
Attributes recipient,
subject
Content
(Body)
13
outgoing
message queue
Electronic Mail user mailbox
user
Three major components: agent
user agents mail
user
server
mail servers agent
SMTP
simple mail transfer mail
protocol: SMTP server user
SMTP agent
User Agent
SMTP
composing, editing, reading user
mail
mail messages server agent
e.g: Outlook, elm, Netscape
Messenger user
agent
outgoing, incoming user
messages stored on server agent
14
Electronic Mail: mail servers
user
Mail Servers agent
mailbox contains mail
incoming messages for user
server
agent
user
SMTP
message queue of mail
outgoing (to be sent) mail server user
messages SMTP agent
16
Scenario: A sends message to B
1) A uses UA to compose 4) SMTP client sends A’s
message and provides message over the TCP
B’s Email address connection
b@@bits-pilani.ac.in 5) B’s mail server places
2) A’s UA sends message to the message in Bob’s
her mail server; message mailbox
placed in message queue
6) Bob invokes his user
3) Client side of SMTP opens agent to read message
TCP connection with B’s
mail server
1 mail
mail
server user
user server
2 agent
agent 3 6
4 5
17
Try SMTP interaction for yourself:
telnet servername 25
see 220 reply from server
enter HELO, MAIL FROM, RCPT TO, DATA, QUIT
commands
above lets you send email without using email
client (reader)
18
Sample SMTP interaction
S: 220 bitsmail01.bits-pilani.ac.in
C: HELO bitsmail01.bits-pilani.ac.in
S: 250 Hello bitsmail01.bits-pilani.ac.in, pleased to meet you
C: MAIL FROM: < rimpy@bits-pilani.ac.in >
S: 250 rimpy@bits-pilani.ac.in... Sender ok
C: RCPT TO: < h2006443@bits-pilani.ac.in >
S: 250 h2006443@bits-pilani.ac.in ... Recipient ok
C: DATA
S: 354 Enter mail, end with "." on a line by itself
C: Do you like ketchup?
C: How about pickles?
C: .
S: 250 Message accepted for delivery
C: QUIT
S: 221 bitsmail01.bits-pilani.ac.in closing connection
19
Java Mail API
21
javax.mail.Session
22
javax.mail.Store
23
javax.mail.Transport
24
javax.mail.Folde
25
javax.mail.Message
26
Example Program
import javax.mail.*;
import javax.mail.internet.*;
/**
* Sends a simple text e-mail message.
*
* @param smtpHost name of the SMTP mail server
* @param from e-mail address of the sender
* @param to e-mail address of the recipient
* @param subject subject of the e-mail message
* @param messageText the actual text of the message
*
* @throws javax.mail.MessagingFormatException problems
sending message
*/
public static void sendMessage(String smtpHost,String from,
String to,String subject, String messageText)
throws MessagingException {
27
Step 1: Configure the mail session
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", " mail.itmindia.edu ");
props.setProperty("mail.user", "emailuser");
Session mailSession =
Session.getDefaultInstance(props);
28
Step 2: Construct the message
Transport transport =
mailSession.getTransport();
transport.connect();
transport.send(testMessage);
System.out.println("Message
sent!");
}
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: java QuickMailText <smtphost> <from>
<to>");
System.exit(1);
}
String smtpHost = args[0];
String from = args[1];
String to = args[2];
String subject = "Test Message - quickmail_text";
StringBuffer theMessage = new StringBuffer();
theMessage.append("Hello,\n\n");
theMessage.append("Hope all is well.\n");
theMessage.append("Cheers!");
try {
QuickMailText.sendMessage(smtpHost, from, to, subject,
theMessage.toString());
}
catch (javax.mail.MessagingException exc) {
exc.printStackTrace();
}
}}
31
Running Java Mail API Programs
(A) Sending E-Mail
---------------
c:\>java <programname> <smtphost> <from> <to>
OR
For example,
OR
32
(B) Retrieving all E-Mails
For example,
For example,
33