|
Welcome to the Java Developer Connection Java Technology Fundamentals Newsletter.
This monthly newsletter provides a way for you to learn the basics of the Java programming language, discover new resources, and keep up-to-date on the latest additions to the JDC's New to Java Programming Center.
Java Programming Language Basics
Networking Basics
The standard Java platform comes with built-in support for network programming, because Internet access and communication is so important. The java.net package, available since version 1.0, and the newer javax.net package (1.4), provide what is needed.
The first aspect of network programming to examine is how to address the other machine you need to talk to. The InetAddress class provides the essentials. Through Internet Protocol (IP) version-specific subclasses, you can identify a host through a raw IP address like 127.0.0.1 or a domain name like java.sun.com.
Once you have an instance of InetAddress, or more specifically one of its subclasses Inet4Address or Inet6Address, you can connect to the machine it identifies. To create an InetAddress, use one of the static methods of the class, most likely getByName or getByAddress. For talking to yourself, there is also getLocalHost.
The first allows you to create an InetAddress with a string like java.sun.com:
InetAddress addr = InetAddress.getByName("java.sun.com");
The second allows you to create an InetAddress from a byte array for the IP address:
InetAddress addr2 = InetAddress.getByAddress (new byte{(byte)192, 18, 97, 71});
Notice the (byte)192 in the above. This actually stores -64 in the array, as bytes have a range of -128 to 127. And, 128 - 192 = ?64.
Once you have an InetAddress, you can try to connect to the machine identified by the address. Machines on the Internet communicate through different protocols, like HTTP for web connections, SMTP for sending mail, and so on. When communicating through a specific protocol, you talk to a specific port that offers the service associated with the protocol. For well-known protocols, there are well known ports:
FTP - 21
SMTP - 25
HTTP - 80
POP3 - 110
HTTPS - 443
This means that for sending mail, typically, you would talk to port 25 on the SMTP server. It could be another port, but it is typically port 25. The port on the client side really doesn't matter, as the server will talk to whomever connects to it.
To talk to a remote system, you need to use the Socket class. When creating a socket connection, you specify the host and port to connect to. You can specify a host through a string like java.sun.com or an InetAddress (which you got yourself by specifying a host through a string like java.sun.com).
Once connected, you communicate with the machine through its InputStream or OutputStream, quite possibly after converting it to a Reader or Writer if the protocol is text-based, like HTTP.
For instance, to fetch a web page from an HTTP web server, you can make a GET request. This takes the form of
GET <URL> HTTP/1.0
Where the <URL> bit identifies the page to fetch, typically just / to get the
home page for a site.
Here's an example that demonstrates fetching a web page from the host name passed in from the command line:
import java.io.*;
import java.net.*;
public class GetWebPage {
public static void main(String args[])
throws Exception {
if (args.length != 1) {
System.err.println("java GetWebPage hostname");
return;
}
String host = args[0];
InetAddress addr = InetAddress.getByName(host);
Socket socket = new Socket(addr, 80);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
pw.print("GET / HTTP/1.0\n\n");
pw.flush();
String line;
while ((line = br.readLine()) != null) { // read until EOF
System.out.println(line);
}
pw.close();
br.close();
}
}
The key line here is the one with the GET call in it:
pw.print("GET / HTTP/1.0\n\n");
Besides specifying which page to fetch (the / here), the command must end with two new line characters. This is not a platform-specific new line / carriage return combo, but instead is always two new lines.
Running the program, saving the output to a file, and viewing that file in a browser will show the default home page for http://java.sun.com/. Some sites show an alternative page if your browser doesn't support frames.
Typically, a browser will make additional requests to fetch the images referenced on a page. As most image links are on a web page with relative links, these are not shown as loaded.
Additional web connections can be made through the Socket class and other protocols, but essentially all the code shown in the GetWebPage is sufficient to communicate with the world.
Test what you learned about networking basics with this online quiz.
Java Bits
Lesson: All About Sockets
URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application.
In client-server applications, the server provides some service, such as processing database queries or sending out current stock prices. The client uses the service provided by the server, either displaying database query results to the user or making stock purchase recommendations to an investor. The communication that occurs between the client and the server must be reliable. That is, no data can be dropped and it must arrive on the client side in the same order in which the server sent it.
TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet use to communicate with each other. To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. To communicate, both the client and the server read from and write to the socket bound to the connection.
Read the rest of this tutorial.
Making Sense of the Java Class
Creating Progress Bars
Progress bars are used in applications to let users know something is happening in the background and they need to wait. Sometimes progress bars appear as files are loading, the application is searching a network, or some other background work is going on. Progress bars usually appear as a graphical bar that grows, as progress is the background is completing.
The Swing API provides a special class for creating progress bars in your applications. Like other components, the JProgressBar inherits from the JComponent class. JProgressBar comes with several useful constructors and methods to allow you to create a progress bar object that is customizable.
There are several ways to display progress bars, such as aligned vertically or horizontally. You can also have a progress bar display text.
To create a progress bar object, call one of the following constructors:
JProgressBar() -- Creates a horizontal progress bar that displays a border but no progress string.
JProgressBar(BoundedRangeModel newModel) -- Creates a horizontal progress bar that uses the specified model to hold the progress bar's data.
JProgressBar(int orient) -- Creates a progress bar with the specified orientation, which can be either JProgressBar.VERTICAL or JProgressBar.HORIZONTAL.
JProgressBar(int min, int max) -- Creates a horizontal progress bar with the specified minimum and maximum.
JProgressBar(int orient, int min, int max) -- Creates a progress bar using the specified orientation, minimum, and maximum.
Progress of background application work is shown graphically on the bar, which can be of any color you choose from the color class. You'll find the following methods useful for customizing the progress bar.
setOrientation(int newOrientation) -- Sets the progress bar's orientation to newOrientation, which must be JProgressBar.VERTICAL or JProgressBar.HORIZONTAL.
addChangeListener(ChangeListener l) -- Adds the specified ChangeListener to the progress bar.
getValue() -- Returns the progress bar's current value, which is stored in the progress bar's BoundedRangeModel.
setValue(int n) -- Sets the progress bar's current value (stored in the progress bar's data model) to n.
getMaximum() -- Returns the progress bar's maximum value, which is stored in the progress bar's BoundedRangeModel.
getMinimum() -- Returns the progress bar's minimum value, which is stored in the progress bar's BoundedRangeModel.
- setString(String s) -- Sets the value of the progress string.
setStringPainted(boolean b) -- Sets the value of the stringPainted property, which determines whether the progress bar should render a progress string.
The following applet load examples of three progress bars, and a button that increments the first progress bar and displays the result in the status bar:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ProgressBarExample extends JApplet
{
JProgressBar jpb1, jpb2, jpb3;
JButton jb;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
//Note the default orientation is horizontal
jpb1 = new JProgressBar();
jpb1.setValue(30);
jpb1.setForeground(Color.red);
jpb1.setStringPainted(true);
jpb1.setString("Please wait. . . ");
contentPane.add(jpb1);
jpb2 = new JProgressBar();
jpb2.setOrientation(JProgressBar.VERTICAL);
jpb2.setForeground(Color.blue);
jpb2.setValue(50);
jpb2.setStringPainted(true);
jpb2.setBorder(BorderFactory.createRaisedBevelBorder());
contentPane.add(jpb2);
jpb3 = new JProgressBar();
jpb3.setOrientation(JProgressBar.VERTICAL);
jpb3.setValue(25);
contentPane.add(jpb3);
jb = new JButton("Increment");
contentPane.add(jb);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jpb1.setValue(jpb1.getValue() + 10);
}
});
jpb1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
showStatus("Value of progress bar 1: " +
jpb1.getValue() + "%");
}
});
}
}
When this applet is run, you should see something similar to the image below:
In the code above, there is a listener for the progress bar and one for the button. Normally you wouldn't increment a progress bar with a button, but instead background application tasks update a progress bar. To understand how this process works, you need to understand thread usage. See For More Information below.
In addition, you may want to consider using the ProgressMonitor class, which will be covered in the next issue, and related links appear below.
Program Challenge
Networking
Create a generic client networking program that graphically does what the GetWebPage example does. This could replace your command-line 'telnet' program.
In addition to prompting for the host name and port, prompt the users for the set of commands to execute and show the results as each is executed. For instance, you can do the GET / HTTP/1.0 command to retrieve a web page after connecting to port 80 on a host or connect to a POP3 server and execute the user, pass, list, and retr commands to fetch your email.
More on the POP3 command set.
See a possible solution to the Challenge.
Sun's Online Courses
Beginning to Program with the Java Programming Language
The Beginning to Program With the Java Programming Language course is designed for students with little or no programming experience who want to learn to program using the Java programming language. This course takes an in-depth look at two of the fundamental concepts of every Java program: Variables and datatypes.
» More
Sun Tech Days, A Developer Conference!
- March 9-10, 2004: Beijing, China
- March 16-17, 2004: Mexico City, Mexico
Packed with information on developer tools and technologies, Sun Tech Days brings high-end innovation and solutions. Register and view a current list of cities and dates.
For More Information
Downloading the Java 2 Platform
For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.
Subscribe to the following newsletters for the latest information about technologies and products in other
Java platforms:
- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to
developers working with core Java technologies.
- Wireless Developer Newsletter. Learn about the latest releases, tools, and resources for developers
working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and
techniques for developing in the Java 2 Platform, Standard Edition (J2SE)
You can subscribe to these and other JDC publications on the JDC Newsletters and Publications
page
IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html
Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com
Go to the subscriptions
page to subscribe or unsubscribe to this newsletter.
ARCHIVES: You'll find the Java Technology Fundamentals Newsletter archives at:
http://developer.java.sun.com/developer/onlineTraining/new2java/supplements/
Copyright 2004 Sun Microsystems,
Inc. All rights reserved. 4150 Network Circle, Santa Clara, CA 95054
Trademark Information: http://www.sun.com/suntrademarks/
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun
Microsystems, Inc. in the United States and other countries.
|