Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Mar 19, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Writing Servers in Java

How can a server written in Java work like a UNIX daemon? To me it seems that a server cannot be an applet. Is it a standalone application?

Writing servers in Java is extremely easy. This is partly due to Java's threading machinery and partly due to the rich set of networking class libraries that comes standard with Java.

Java servers are standalone Java applications (as opposed to applets) that run by themselves much as a UNIX daemon would. What's amazing however, is that Java servers are platform-independent and take substantially fewer lines of code to write compared with the same programs written in C or C++.

Standalone Java server are started by directly invoking the Java interpreter on the Java class defining the main() method. Once started, the program typically binds and listens to a UDP or TCP port number and waits for incoming connections over the network. This works on any system supporting the TCP/IP protocol suite, be it a UNIX system or a Windows NT system. As soon as a connection request is detected, the program would either serve the request directly or spawn a Java thread to handle the request, and goes right back to listening to the port again.

Fundamental to the operation of Java servers is the ServerSocket class which is a standard part of the java.net package. As an example, the following is a simple Java date server that binds to TCP port 13000 and for every incoming request, provides the current date and time. To invoke the server, you simply need to run the Java interpreter and give it the name of the class file as follows:

        java DateServer

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

public class DateServer {

        public static void main(String argv[]) throws IOException {
                ServerSocket serverSocket;
                Socket s;
                String peer;
                PrintStream commandOut;
                int port = 13000;

                serverSocket = new ServerSocket(port);

                while (true) {
                        s = serverSocket.accept();
                        commandOut = new PrintStream(new BufferedOutputStream(
                                                s.getOutputStream()), true);

                        commandOut.println("The current time is " + new Date());

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date