Java - How to Create a Simple Server Using Java Socket
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.
Difficulty
- Basic
Tutorial Contents
Creation of Server
We are still using the previous project (Sample) to expand this tutorial. Open IntelliJ IDEA, right click onSample/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"); } }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
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:
- https://docs.oracle.com/javase/7/docs/api/, select
java.net
in the Packages menu (top of left-side navigation), then find and hitServerSocket
in the Classes (below of Packages). - https://developer.android.com/reference/java/net/ServerSocket.html#accept()
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 theclient.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; } } } }
Creation of Launcher
Just defined the
main
method, create an instance ofServer
and pass234
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 hitEnter
at all.
Result
Server's Log
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
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
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
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