ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

How to build a server in Java: Part 1 - Creating the server

Updated on June 16, 2012

Servers in Java

A server in Java is built using ServerSockets which enable you to access the outside world. For this part of the tutorial we will be building the actual server. We will not be building the client-side application (way to connect to the server) in this tutorial but you can check it out in Part 2.

Here is an example of a ServerSocket, the number that you pass it's constructor is the port number you will allow connection through. Ports are essentially the outlet through which you can access and send data to the outside world.

ServerSocket sSocket = new ServerSocket(5000);

Now that you've set up the ServerSocket you can create a socket to wait for an incoming request. This next example builds onto the previous one. A ServerSocket is used to specify a port and then you create a socket to send and receive data through that port.

ServerSocket sSocket = new ServerSocket(5000);
Socket socket = sSocket.accept();

The accept() method for the socket tells the computer to wait until a connection has been established. This will hold up the program and wait for a client to connect.

In order to send and receive information through that port I talked about earlier we need to set up a PrintWriter to send data and a BufferedReader to read in the input. Below is an example of how to do that.

PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

Here are some example of writing and reading.

output.println("Hello World");

String inputString = input.readLine();

Let's get coding!

Okay so now that all the explanations are out of the way lets get coding! We could build a server that allows a client to connect to it and leave it at that. That would be cool, but not very useful or exciting. So how about we build ourselves a chat server, alright? Okay!

import java.util.*;

public class Server
    public static void main(String[] args)
        new Server();
    public Server() 
        //We need a try-catch because lots of errors can be thrown
        try {
            ServerSocket sSocket = new ServerSocket(5000);
            System.out.println("Server started at: " + new Date());
            //Wait for a client to connect
            Socket socket = sSocket.accept();
            //Create the streams
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //Tell the client that he/she has connected
            output.println("You have connected at: " + new Date());
            //Loop that runs server functions
            while(true) {
                //This will wait until a line of text has been sent
                String chatInput = input.readLine();
        } catch(IOException exception) {
            System.out.println("Error: " + exception);

The Explanation

  • So, first we import our needed files and create our class, I called my class Server (yah, pretty creative).
  • Then we create a try-catch because there are lots of errors that can possibly be thrown!
  • Next we create a ServerSocket that uses port 5000.
  • After that we wait for a client to connect to the server.
  • Once a connection is established we set up the PrintWriter and Buffered reader then we send a message to the client letting him/her know that a connection has been made.
  • Here is the most important part, the while loop is where all the server functions will go, it will run infinitely and continue waiting for the client to send it information.

And that's it, this is a very simple server but it will do the job. Head on over to Part 2 to figure out how to connect to the server and send and receive information from it.


    0 of 8192 characters used
    Post Comment

    • profile image

      Klaus Isaac 2 years ago

      that was great, i imagined it to be something really massive and scary but you have made it quite simple and understandable. Thanks very much

    • Drenguin profile image

      Drenguin 5 years ago from Somewhere

      Thanks! I hope you like it!

    • MyWebs profile image

      Anthony Goodley 5 years ago from Sheridan, WY

      I'm learning Java now so I'm very happy to I found your how to create a server in Java series. Thanks for this great hub. My next day off I'm going to give this a try in Eclipse. Voted up and as useful.

    • klanguedoc profile image

      Kevin Languedoc 6 years ago from Canada

      Great tutorial. I have often heard of being to create a server in Java but I didn't it was that simple. I give it a try after I have read your part 2 & 3. Thanks. Also thanks for following me.