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

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
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 $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
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 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... 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
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
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.