TweetFollow Us on Twitter

Java Net Classes
Volume Number:12
Issue Number:10
Column Tag:Java Tech

Java Net Classes

Writing Java code to access the Internet is a snap

By Christopher Evans

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

A large part of Java’s appeal is that much of what of we used to spend those days, nights and weekends doing is now taken care of for us. Memory management, threading and networking are trivial endeavors in Java. In this article, I show exactly how simple it is to use the networking classes that come with Java. Collectively, these are referred to as the java.net package, and they contain things like URL content handlers, and stream and datagram socket classes.

Getting a URL

Since much of the Java class library was written to facilitate the creation of the Hot Java Web browser, accessing a URL is pretty simple. Here’s how to get the text content of a URL in Java; you must admit, things don’t come much easier than this:

public static String GetTextURL(String url_address)
{
 URL  url = new URL(url_address);
 return (String)url.getContent();
}

If you were to call this method with a hard-coded URL, it would return a string containing the text content of that URL. This string could then be dumped to standard out, or it could be parsed as part of a larger Web access application. Here, we just do the former:

String roaster_info = GetTextURL(“http://www.roaster.com”);
System.out.println(roaster_info);

It’s this easy for almost any type of data for which there is a content handler. By default, JDK 1.0.2 comes with content handlers for text and images (GIF or JPEG), but you can write your own content handlers by subclassing java.net.ContentHandler and converting the MIME data type into an object that can be understood by the application or applet.

A Simple Syslog Server...

Creating Java applications or applets that do more on the Net isn’t much more complicated. Traditionally, network programming, particularly on the Macintosh, has been reserved for a few stalwart engineers - the guys who sat in the corner, surrounded by routers, deferred to by those not educated in the black art of protocol stacks and socket streams. The java.net package makes it possible for more developers to take advantage of the really cool things you can do once you begin communicating over a network.

Since Java was designed to work over the Internet, the only network protocol supported is TCP/IP; but you can be pretty sure that this will be available on just about any machine you can buy these days.

The following example shows how to create a very basic server. This server implements the Unix syslog program. It opens a UDP (User Datagram Protocol) socket on port 514 and waits for some data to come in. When data arrives on the port, it is received and dumped into a text file. The real syslog allows you to have different levels of messages that go to different files, but I think this gives you a pretty good idea of what is involved in creating a basic UDP server application.

Note that UDP is known as an unreliable protocol, because you are not guaranteed to receive data that is sent to your port. If reliability is important, then you should use the TCP protocol, which makes sure that if a packet is sent and it’s possible for it to be received, then it will be received. For a simple message-logging program like this, though, UDP is sufficient.

JavalogServer.java
/*
    JavalogServer.java
    
    A very basic implementation of syslog in Java using UDP datagram
    sockets
    
    By Christopher Evans
    Copyright © 1996 Natural Intelligence, Inc.
*/
import java.net.*;
import java.io.*;

/**
Implements a basic syslog server receiving data on port 514 and
logging it to a file called syslog.log
*/ 

public class JavalogServer
{
 
 public static void main(String args[]) throws Exception
 {
    //Create the buffer to store the data as it comes in
 byte[] log_buffer = new byte[2048];
 
 int    received_messages = 0;
 
    //Open the file for writing the log messages
 File   out_file = new File(“syslog.log”);
 
    //Create the output stream so we can dump the data
 FileOutputStream syslog_file =
 new FileOutputStream(out_file);
 
    //Create a DatagramPacket to receive the incoming log data
 DatagramPacket packet = 
 new DatagramPacket(log_buffer, log_buffer.length);
 
    //Create a socket that listens on the net
 DatagramSocket socket = new DatagramSocket(514);
 
 while(received_messages < 5) 
 {
    //Wait until some data arrives. Aren’t threads great?
 socket.receive(packet);
 
    //Increment the message count
 received_messages++;
 
    //Build a string of the packet data
 String packet_string = 
 new String(log_buffer, 0, 0, packet.getLength());
 
    //Put the packet data after a bit of header so we can see where it comes from
 String out_string = “<syslog from “ + \
 packet.getAddress().getHostName() + “>” + \
 packet_string + “\n”;
 
    //Print the message to the standard out window
 System.out.println(out_string);
 
    //Convert the message to an array of bytes so it can be sent to the file
 int msg_len = out_string.length();
 
 byte[] out_buffer = new byte[msg_len];
 
 out_string.getBytes(0, out_string.length(), 
 out_buffer, 0);

    //Write the name of the host where the data came from to the file
 syslog_file.write(out_buffer, 0,
 out_string.length());
 
 }
 socket.close();
 } 
}

This Java application starts by creating a 2K buffer to store the messages in as they arrive. Then it creates a file called syslog.log in the same directory as the application, and opens an output stream to that file. Next, it creates a DatagramPacket object, giving it the buffer created earlier as its place to store the network packets as they come in, and a DatagramSocket object, passing it the port where it should be listening.

After all of this initialization is done, the JavalogServer calls socket.receive and passes it the DatagramPacket object. The DatagramSocket object will wait until some data has arrived in the port before returning. When data does arrive, that data is immediately written out to the file, and socket.receive is called again. For this example, our server quits after receiving five messages, but in the real world, syslog continually waits for the next message to arrive.

Since Java is running on its own virtual machine, and since that virtual machine is preemptively scheduled, the machine can do other things while the JavalogServer is waiting for a message to arrive.

When you run this on some of the applet runners on the Mac, you will find that there is no way to quit the server process. It would not be hard to add a menu with AWT that would allow you to quit; for now, it will quit when it receives the fifth message.

...And a Simple Syslog Messenger

What good is a server without a client? Next, I am going to show how easy it is to send data across a network. JavalogClient gets its target host machine, and the message to send, from the command line; then it sends the message to the host.

JavalogClient.java
/*
    JavalogClient.java
    
    A very basic implementation of a syslog message dispatcher in Java 
    using UDP datagram sockets
    
    By Christopher Evans
    Copyright © 1996 Natural Intelligence, Inc.
*/


import java.net.*;
import java.io.*;

/**
    Implements a basic syslog client, sending data to port 514 on
    the machine whose name is passed in as a command line argument
*/ 

public class JavalogClient {

 public static void main(String args[]) throws Exception
 {
 if(args.length != 2) {
 System.out.println(“Usage: JavalogClient <host> \
   <message>”);
 System.exit(0);
 }
 
    //Create an InetAddress object and initialize it from the first argument
    //which should be a host name like natural.natural.com
 InetAddress address = InetAddress.getByName(args[0]);
 
    //Find out how long the message is, then copy it from a java.lang.String
    //into an array of bytes to be sent.
 int msg_len = args[1].length();
 
 byte[] message = new byte[msg_len];
 
 args[1].getBytes(0,msg_len, message,0);
 
    //Create a DatagramPacket object with the data that the user wants to send
 DatagramPacket packet = 
 new DatagramPacket(message, msg_len, address, 514);
 
    //Create a new datagram socket to send the packet
 DatagramSocket socket = new DatagramSocket();
 
    //Now actually send the data across the network
 socket.send(packet);
 
    //Clean up the socket so it isn’t left open
 socket.close();
 
 }
}

The client is even smaller than the server. The user sends a message with command line arguments like this:

host.natural.com “This is a test of the emergency Javalog system”

This would result in a line in the log file that would look something like this:

<syslog from evans.natural.com.> This is a test of the emergency Javalog 
system

First we create an InetAddress object based on the host name passed in as the first command-line argument (“host.natural.com”, in the example). Then we take the second command-line argument and convert it from a java.lang.String object into an array of bytes, just as we did in the JavalogServer example. (In case you are wondering, this is necessary since Java strings are stored as Unicode strings where each character is two bytes. If you want to send straight ASCII across the network or store the string in a text file, you must first convert it to an array of bytes.)

After the message is created, we create a java.net.DatagramPacket object containing everything we need to know in order to send the data, including the host name, the socket on that host, and the message data itself. Then we create the java.net.DatagramSocket object, which actually opens the TCP/IP socket for sending the data. The final steps are to send the packet and to close the socket.

The client could also be cleaned up with a nice AWT interface allowing you to enter the host name in one text field and the message in another, but I wanted to make it clear how simple it is to implement basic networking in Java.

Further Reading

For more information on the java.net classes, you might want to check out the following sources:

Lemay, Laura, and Charles Perkins, with Timothy Webster. Teach Yourself Java For Macintosh in 21 Days. Hayden Books. 1996.

David Flanagan. Java in a Nutshell. O’Reilly & Associates, Inc. 1996.

JavaSoft WWW:

http://java.sun.com/java.sun.com/products/JDK/1.0.2/api/javaf.htm

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »
Play Together teams up with Sanrio to br...
I was quite surprised to learn that the massive social network game Play Together had never collaborated with the globally popular Sanrio IP, it seems like the perfect team. Well, this glaring omission has now been rectified, as that instantly... | Read more »
Dark and Darker Mobile gets a new teaser...
Bluehole Studio and KRAFTON have released a new teaser trailer for their upcoming loot extravaganza Dark and Darker Mobile. Alongside this look into the underside of treasure hunting, we have received a few pieces of information about gameplay... | Read more »
DOFUS Touch relaunches on the global sta...
After being a big part of a lot of gamers - or at the very least my - school years with Dofus and Wakfu, Ankama sort of shied away from the global stage a bit before staging a big comeback with Waven last year. Now, the France-based developers are... | Read more »

Price Scanner via MacPrices.net

Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more
Updated Mac Desktop Price Trackers
Our Apple award-winning Mac desktop price trackers are the best place to look for the lowest prices and latest sales on all the latest computers. Scan our price trackers for the latest information on... Read more
9th-generation iPads on sale for $80 off MSRP...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80 off MSRP on their online store for a limited time. Prices start at only $249. Sale prices for online orders only, in-store prices... Read more
15-inch M3 MacBook Airs on sale for $100 off...
Best Buy has Apple 15″ MacBook Airs with M3 CPUs on sale for $100 off MSRP on their online store. Prices valid for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
24-inch M3 iMacs now on sale for $150 off MSR...
Amazon is now offering a $150 discount on Apple’s new M3-powered 24″ iMacs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 24″ M3 iMac/8-core GPU/8GB/256GB: $1149.99, $150... Read more
15-inch M3 MacBook Airs now on sale for $150...
Amazon is now offering a $150 discount on Apple’s new M3-powered 15″ MacBook Airs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 15″ M3 MacBook Air/8GB/256GB: $1149.99, $... Read more
The latest Apple Education discounts on MacBo...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Retail Assistant Manager- *Apple* Blossom Ma...
Retail Assistant Manager- APPLE BLOSSOM MALL Brand: Bath & Body Works Location: Winchester, VA, US Location Type: On-site Job ID: 04225 Job Area: Store: Management Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now See Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.