Sockets provide connections between applications
and allow streams of data to flow. Sockets are fairly straightforward
to set up in Java. Java provides two kinds of sockets:
-
Socket:
provides a connection-oriented protocol that behaves like telnet
or ftp. The connection remains active, even with no communications
occurring, until explicitly broken.
- DatagramSocket:
- a connectionless protocol
- transfers datagram packets
- no fixed connection
- does not keep packets in order
- no guarantee a packet will arrive at its destination
The class ServerSocket
is not a socket per se, but it monitors a given port and returns
a Socket
object when a client attempts to connect to that port.
We will talk more about sockets and ServerSocket
in Chapters 14 and Chapter
15.
The demonstration program WhoisApplet
shown below illustrates how to run the whois
internet operation that returns information about a given domain
name. The registry site whois.internic.net
provides this service from anywhere on the internet.
The code segment shows how to create a socket that connects a stream
to port 43 at the remote site. An output stream is obtained from
the socket and a PrintWriter
wrapped around it. This is then used to send a whois query to that
socket.
Similarly, an input stream is obtained from the socket and wrapped
first with an InputStreamReader
and then a BufferedReader.
The latter class provides the readLine()
routine or obtained a whole line of text at one time from the whois
output. You can enter other domain names in the text field.
Though written in applet form, the security manager in most browser
JVMs will block accesses to IP addresses other than the source of
the applet. So we only show an image of a typical output. You can,
however, run the program as an application or an appletviewer.
WhoisApplet
WhoisApplet
operations are blocked by the JVM security manager
in most browsers but you can run it in standalone mode instead.
Below we show an image of an example of the program in action:
|
import
javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;
/** This program displays the whois output in a text area
**/
public class WhoisApplet extends JApplet
implements ActionListener
{
// A Swing textarea for display of string info
JTextArea fTextArea = null;
JTextField fTextField = null;
String fFileToRead="data.txt";
//Buttons
JButton fGoButton;
JButton fClearButton;
JButton fExitButton;
// Flag for whether the applet is in a browser
// or running via the main () below.
boolean fInBrowser = true;
public void init () {
// Create a User Interface with
a textarea with sroll bars
// and a Go button to initiate processing
and a Clear button
// to clear the textarea.
Container content_pane = getContentPane
();
JPanel panel = new JPanel (new BorderLayout
());
// Create an instance of DrawingPanel
fTextArea = new JTextArea ();
fTextArea.setEditable (false);
fTextArea.setLineWrap (true);
// Add to a scroll pane so that
a long list of
// computations can be seen.
JScrollPane area_scroll_pane = new
JScrollPane (fTextArea);
panel.add (area_scroll_pane,"Center");
fTextField = new JTextField ("sun.com",
10);
// If return hit after entering
text, the
// actionPerformed will be invoked.
fTextField.addActionListener (this);
fGoButton = new JButton ("Go");
fGoButton.addActionListener (this);
fClearButton = new JButton ("Clear");
fClearButton.addActionListener (this);
fExitButton = new JButton ("Exit");
fExitButton.addActionListener (this);
JPanel control_panel = new JPanel
();
control_panel.add (fTextField);
control_panel.add (fGoButton);
control_panel.add (fClearButton);
control_panel.add (fExitButton);
panel.add (control_panel,"South");
// Add text area with scrolling
to the contentPane.
content_pane.add (panel);
} // init
/** Connect to the whois service via a socket.
Write the
* address with a PrintWriter
object and read the output
* via a BufferedReader.
Send the output to the text area.
**/
public void whoisConnect ( String queryAddress)
{
int port = 43; // Standard whois
port
String reply;
try {
Socket whois_socket
=
new Socket
("whois.internic.net", port);
PrintWriter print_writer
=
new PrintWriter
( whois_socket.getOutputStream (),true);
print_writer.println
(queryAddress );
InputStreamReader input_reader
=
new InputStreamReader
(whois_socket.getInputStream ());
BufferedReader buf_reader
=
new BufferedReader
(input_reader);
while ( (reply
= buf_reader.readLine ()) != null) {
// Write
the whois info to the textarea.
fTextArea.append
(reply + '\n');
}
fTextArea.append ("\n\n");
// Add space between queries
} catch (IOException
e ){
fTextArea.append ("IO
Exception = "+e);
System.out.println
("IO Exception = "+e);
return;
}
} // whoisConnect
/** Respond to the buttons **/
public void actionPerformed (ActionEvent e)
{
Object source = e.getSource ();
if (source == fGoButton
|| source == fTextField ) {
String query = fTextField.getText
();
if (query
== null || query.length () <=1 )
fTextArea.setText ("Error: Bad host entry");
else
try {
whoisConnect
(query);
}
catch (Exception
ec) {
fTextArea.append(
"\n\n Error attempting to connect to WhoIs!\n");
fTextArea.append("Exception
= \n" + ec);
}
} else if (source ==
fClearButton)
fTextArea.setText
(null);
else if (!fInBrowser)
System.exit
(0);
} // actionPerformed
/** Display the println string on the text area
**/
public void println (String str) {
fTextArea.append (str + '\n');
}
/** Display the print string on the text area
**/
public void print (String str){
fTextArea.append (str);
}
public static void main (String[] args) {
//
int frame_width=450;
int frame_height=300;
//
WhoisApplet applet = new WhoisApplet
();
applet.fInBrowser = false;
applet.init ();
// Following anonymous class used
to close window & exit program
JFrame f = new JFrame ("whois Demo");
f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// Add applet to the frame
f.getContentPane ().add ( applet);
f.setSize (new Dimension (frame_width,frame_height));
f.setVisible (true);
} // main
}// class WhoisApplet
|
References & Web Resources
Latest update: Dec. 8, 2004
|