Java - How to Create a Simple Server Using Java Socket

in #utopian-io7 years ago (edited)

Java_programming_language_logo.svg.png
Source here.

What Will I Learn?

In this tutorial, I will guide you the fundamentals of creating a simple server using Java socket. We will try connecting to the server using telnet to address: 127.0.0.1, and port 234.

  • Java Socket Connection
  • Java Concurrency by Using Thread

Requirements

  • Any current JDK.
  • IntelliJ IDEA
  • If you are comfortable using the Windows platform, make sure to do this following:
    • Open Control Panel,
    • Select Programs, then choose Turn Windows features on or off,
    • Finally, find and checked Telnet Client.
      Untitled 001.png

Difficulty

  • Basic

Tutorial Contents

  • Creation of Server
    We are still using the previous project (Sample) to expand this tutorial. Open IntelliJ IDEA, right click on Sample/src/main/java, select New > Java Class, then on opened pop-up dialog, type: com.murez.branch.net.Server. Server class just have two actions, i.e.:

    • Start, to start this server, and
    public void start() {
       . . .
    }
    
    • Close, to stop this server.
    public void close() {
       . . .
    }
    

    And this is the source code of Server,

    
       public class Server implements AutoCloseable {
           private ServerSocket server;
           private Runner runner;
           private int port;
       
    public Server(int port) { if((this.port = port) < 0 || port > 0xFFFF) throw new IllegalArgumentException("Port value out of range: " + port); }
    public void start() throws IOException { if(server == null) { server = new ServerSocket(); server.bind(new InetSocketAddress("localhost", port)); runner = new Runner(server); runner.start(); System.out.println("Server's starting"); } else throw new IllegalArgumentException("Server's already started"); }
    public void close() throws Exception { if(!server.isClosed()) { server.close(); server = null; System.out.println("Server has closed"); } else throw new IllegalArgumentException("Server's already closed"); } }

    Untitled 002.png

    Next, we need to define the Runner. Why is the Runner?
    The Runner is a separate process that will monitor all of incoming connections from client via telnet.
    Imagine if we do not define it, next statement below will never be executed forever since there's no client attempts to reach the server
    Untitled 003.png

    So the solution is to separate it (action when the server accepts the client connection) from the normal flow using Thread like we did at first.

    As mentioned in the Java API, server.accept() listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made and return the new socket.

    References:

    Here's the complete implementation of Runner, we solve it with Runner as a static inner class.
    Next, Runner will also create a new Thread, which each of them will send a short message to the client. We can send a message to the client via the client.getOutputStream() method.
    To see the result clearly, we only add delay for 3 seconds before connection to client closed.

    
       private static class Runner implements Runnable, AutoCloseable {
           private final Object LOCK = new Object();
           private final ServerSocket SERVER;
           private boolean up;
           private Thread t;
       
    private Runner(ServerSocket server) { SERVER = server; }
    public void run() { for(;;) { try { Socket client = SERVER.accept(); new Thread(() -> { SocketAddress address = client.getRemoteSocketAddress(); System.out.println("New client: " + address); try(OutputStream out = client.getOutputStream();) { out.write((address + " > Hello from Server!").getBytes()); // Going to close after 10 seconds Thread.sleep(10000); out.write((System.lineSeparator() + "Say good bye from Server!").getBytes()); out.flush(); } catch(Exception e) { e.printStackTrace(); } }).start(); } catch(IOException e) { break; } synchronized(LOCK) { if(!up) break; } } }
    public void start() { synchronized(LOCK) { if(!up) { up = !up; (t = new Thread(this)).start(); } } }
    public void close() { synchronized(LOCK) { if(up) { t.interrupt(); t = null; up = false; } } } }

    Untitled 004.png

  • Creation of Launcher

    Just defined the main method, create an instance of Server and pass 234 as port number. Finally, start it.
    As seen below,

    
       package com.murez.branch.net;
       
    import java.io.IOException;
    public class Main { public static void main(String[] args) { Server server = new Server(234); try { server.start(); } catch(IOException e) { e.printStackTrace(); } } }

Test
  • We just need two clients to demonstrate. So, open two Command Prompts, type: telnet localhost 234, then hit Enter at all.
    Result
    Untitled 005.png
    Server's Log
    Untitled 006.png

Congratulations! We have successfully created a simple server using Java socket.


Thank you!

Share with heart

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Semoga vote nya gede haha

Hey @murez-nst I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x