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

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
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 »

Price Scanner via MacPrices.net

Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.