silveira neto

carbon-based lifeform. virgo supercluster

Menu Close

The Caps Lock Java Socket Server

Here is a simple server for those who are starting studying sockets or just needs a simple socket server example for reuse while writing your own behavior.

Features:

  • A client should enter a string and the server would answer the same string, with each symbol in up case, when possible.
  • Default port at 8080.
  • One client at time.
  • No multi threading. I said its a simple server.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server {
	private static final int DEFAULT = 8080;
 
	public Server() {
		this(DEFAULT);
	}
 
	public Server(int port) {
		ServerSocket sock;
 
		try {
			sock = new ServerSocket(port);
			System.out.println(String.format("Listening on port %d.", port));
 
			while (true) {
				try {
					Socket client = sock.accept();
					System.out.println("A new connection was accepted.");
 
					BufferedReader in = new BufferedReader(
							new InputStreamReader(client.getInputStream()));		
					OutputStreamWriter out = new OutputStreamWriter(client
							.getOutputStream());
					String input = "";
 
					while (!input.equals("exit")) {
						input = in.readLine();
						if (input.equals("shutdown")) {
							System.exit(0);
						}
						out.write(input.toUpperCase() + "\r\n");
						out.flush();
					}
 
					in.close();
					out.close();
					client.close();
					System.out.println("Connection closed.");
				} catch (NullPointerException npe) {
					System.out.println("Connection closed by client.");
				}
			}
		} catch (IOException ioe) {
			System.err.println(ioe);
			System.exit(-1);
		}
	}
 
	public static void main(String[] args) throws IOException {
		new Server();
	}
}

Usage:

$ javac Server.java
$ java Server
Listening on port 8080.

In another terminal:

$ telnet localhost 8080
Trying ::1…
Connected to localhost.
Escape character is ‘^]’.
hi
HI
The quick brown fox jumps over the lazy dog.
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
exi
EXI
exit
EXIT
Connection closed by foreign host.

© 2016 silveira neto. All rights reserved.

Theme by Anders Norén.