Programming A TCP Socket In JAVA

You must be aware of what network sockets are and what is their use. In this tutorial, we will be using JAVA to create a simple TCP socket . We would be using the console for this tutorials but you can compile your code using Netbeans as well

Server Side Code

package simple_tcp_2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	
	public Server() throws Exception {
		
		ServerSocket server_socket = new ServerSocket(2020); //opening a new port
		System.out.println("Port 2020 is open.");
		
		Socket socket = server_socket.accept();
		System.out.println("Client " + socket.getInetAddress() + " has connected.");
		
		// I/O buffers:
		BufferedReader in_socket = new BufferedReader(new InputStreamReader (socket.getInputStream()));
		PrintWriter out_socket = new PrintWriter(new OutputStreamWriter (socket.getOutputStream()), true);
		String message;
		int secret_number = (int)(Math.random()*10+1);
		
		do {
			out_socket.println("Guess a number [1-10]: ");
			message = in_socket.readLine();
		} while (!(Integer.parseInt(message)==secret_number));
		
		out_socket.println("You got it!!!");
		System.out.println("Secret number is out. Exiting the app.");
		
		socket.close();
		System.out.println("Socket is closed.");
	}
	
	public static void main(String[] args) {
		try {
			new Server();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}

As you can see, here we create a socket that closes when the user guesses the random number generated by it.

Client Side Code

package simple_tcp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

	public Client() throws Exception {
		
		Socket socket = new Socket("localhost",2020);
		System.out.println("Successful connection to the server.");
		
		// I/O streams
		BufferedReader in_socket = new BufferedReader (new InputStreamReader (socket.getInputStream()));
		PrintWriter out_socket = new PrintWriter (new OutputStreamWriter (socket.getOutputStream()), true);
		
		String message = in_socket.readLine();
		System.out.println("Server says: " + message);
		out_socket.println("Thanks!");
		
		socket.close();
		System.out.println("Socket closed.");
		
	}
	
	public static void main(String[] args) {
		try {
			new Client();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}

Navigate to the file path using the cd command ,compile your code using javac and execute it using java .