Source here.
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.
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.:
public void start() {
. . .
}
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.netin the Packages menu (top of left-side navigation), then find and hitServerSocketin 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 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;
}
}
}
}
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(); }
}
}
telnet localhost 234, then hit Enter at all.Congratulations! We have successfully created a simple server using Java socket.
Share with heart