So I started learning Java at the Beginning of this Year…
This is just one of the example programs I tried out that I really liked. It is a simple echo server. It receives a message from a client, then sends that message back. Here is the code:
package simpleserver; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import java.io.PrintWriter; /** * * @author bacpeters */ public class SimpleServer { /** * @param args the command line arguments */ public static void main(String[] args) { if (args.length < 1) { System.err.println("Usage: java SimpleServer <port number>"); System.exit(0); } int portNumber = Integer.parseInt(args[0]); System.out.println("Listening for client on port: " + portNumber); try (ServerSocket serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) { System.out.println("Client connected on port: " + portNumber); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Received message: " + inputLine); out.println("Back at ya: " + inputLine); } in.close(); out.close(); } catch (IOException e) { System.out.println(e); } } }
In the Project Properties, Run category, I configure the desired port number to be passed into the program when I hit “Run”:
After starting the program, I connect to the server via Terminal using Telnet:
telnet <ip> <port>
Then I just type a message and wait to receive the echoed response.
To get started with socket programming with Java 8, start here.