devxlogo

Writing Servers in Java

Writing Servers in Java

Question:
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?

Answer:
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());                        s.close();                }        }}

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist