Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
67 views

Advanced Socket Programming Socket Timeouts Interruptible Sockets Half-Close Internet Address Java Mail Messaging System

This document provides an overview of advanced socket programming concepts in Java including socket timeouts, interruptible sockets, half-close functionality, and internet addressing. It also summarizes the Java Mail API and how email systems work at a high level involving user agents, mail servers, and the SMTP protocol.

Uploaded by

Achint Khanijo
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Advanced Socket Programming Socket Timeouts Interruptible Sockets Half-Close Internet Address Java Mail Messaging System

This document provides an overview of advanced socket programming concepts in Java including socket timeouts, interruptible sockets, half-close functionality, and internet addressing. It also summarizes the Java Mail API and how email systems work at a high level involving user agents, mail servers, and the SMTP protocol.

Uploaded by

Achint Khanijo
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 33

Contents

 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

E-mail Sender SMTP Server

messages

E-mail Recipient POP3 Server

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

 The header contains the information about the message, such


as the sender, recipient, subject and time stamp.
 The actual content of the message is contained in the body part.

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

 SMTP protocol between SMTP


mail servers to send user
mail
email messages server agent
 client: sending mail
server user
agent
 “server”: receiving user
mail server agent
15
Electronic Mail: SMTP
 uses TCP to reliably transfer email message from
client to server, port 25
 direct transfer: sending server to receiving server
 three phases of transfer
 handshaking (greeting)
 transfer of messages
 closure
 command/response interaction
 commands: ASCII text
 response: status code and phrase
 messages must be in 7-bit ASCII

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

 The JavaMailAPI provides classes that model


a mail system.
 Java Mail API is a simple and handy tool for
implementing mail/messaging functionality
in your applications.
 The JavaMail API provides a set of abstract
classes that model a mail system. The API
provides a platform independent and
protocol independent framework to build
Java technology-based mail and messaging
applications 20
 Core classes of this API are
 javax.mail.Session, javax.mail.Store,
javax.mail.Transport,
javax.mail.Folder, and
javax.mail.Message.

21
javax.mail.Session

 The javax.mail.Session class is the


top-level entry class for the Java Mail
API, and its most commonly used
methods provide the ability to control
and load the classes that represent
the service provider implementations
(SPI) for various mail protocols

22
javax.mail.Store

 The javax.mail.Store class is


implemented by a service provider,
such as a POP Mail implementation
developer, and allows for read, write,
monitor, and search access for a
particular mail protocol.

23
javax.mail.Transport

 The javax.mail.Transport class is


another provider-implemented class
and is used for sending a message
over a specific protocol.

24
javax.mail.Folde

 The javax.mail.Folder class is


implemented by a provider; it gives
hierarchical organization to mail
messages and provides access to e-
mail messages in the form of
javax.mail.Message class objects

25
javax.mail.Message

 The javax.mail.Message class is


implemented by a provider and
models all the details of an actual e-
mail message, such as the subject
line, sender/recipient e-mail address,
sent date, and so on

26
Example Program
import javax.mail.*;
import javax.mail.internet.*;

public class QuickMailText {

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

System.out.println("Configuring mail session for: " +


smtpHost);
java.util.Properties props = new java.util.Properties();

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

System.out.println("Constructing message - from=" +


from + " to=" + to);
InternetAddress fromAddress = new
InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage testMessage = new
MimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientTy
pe.TO, toAddress);
testMessage.setSentDate(new java.util.Date());
testMessage.setSubject(subject);
testMessage.setText(messageText);
System.out.println("Message constructed");
Step 3: Now send 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

java <programname> <smtphost> <from> <to> <filetoattach>

For example,

java QuickMailText mail.itmindia.edu xyz.cs@itmindia.edu rimpy@itmindia.edu

OR

java QuickMailAttach mail.itmindia.edu xyz.cs@itmindia.edu rimpy@itmindia.edu


a.html

32
(B) Retrieving all E-Mails

c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90


<programname> <pop3host> <user> <password>

For example,

c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90


MessageList 192.168.0.1 rimpy abc

(C) Viewing Message Contents of an E-Mail


-------------------------------------

c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90


<programname> <pop3host>
<user> <password> <messagenumber>

For example,

c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90


MessageView 192.168.0.1 rimpy abc 2

33

You might also like