StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Friday, August 29, 2014

Java TCP/IP Sockets

 August 29, 2014     Java     No comments   

TCP/IP Introduction

TCP/IP (Transmission Control Protocol/ Internet Protocol) is the protocol of the internet used to interconnect hosts. TCP/IP  provides reliable communication between 2 end points. This article provides an introduction to work with TCP/IP Sockets using Java.

A Socket is an end point of communication flow and is a combination of IP address and a port number. In the TCP/IP world processes that provide services are referred as servers and they typically create sockets and listen for any client processes to connect.

Java support two types of TCP sockets.
  1. ServerSocket - ServerSocket class is a listener which waits for client to connect. ServerSocket is used for TCP/IP servers.
  2. Socket - Socket class is for clients and they are used to connect to server sockets.

TCP/IP Server example in Java

The ServerSocket class is used to create servers. Typically we create the ServerSocket instance with the port number to be published for client connections. ServerSocket has the accept() method which waits for client connections. In the example below we use a ClientHandler thread which simply reads the message from client and writes back a message to client.
package com.sourcetricks.server;

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

public class JavaServer {

  private static class ClientHandler extends Thread {

    private Socket socket;
    
    ClientHandler(Socket socket) {
      System.out.println("Client connected");
      this.socket = socket;
    }
    
    @Override
    public void run() {
      
      try {
        // Reader and writer
        BufferedReader reader = new BufferedReader
            (new InputStreamReader(socket.getInputStream()));
        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
        
        // Read message from client
        System.out.println(reader.readLine());
        
        // Write a message back to client
        writer.println("Hello from server");
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          socket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    
  }
  
  public static void main ( String[] args ) {
    final int port = 8888;
    
    try ( ServerSocket ss = new ServerSocket(port) ) {
      System.out.println("Listening ...");
      while ( true ) {
        Socket socket = ss.accept();
        new ClientHandler(socket).start();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

TCP/IP Client example in Java

The Socket class is used for client connections. The client connects on the published port of the server. Please note the usage of InetAddress class in Socket constructor. Refer to tutorials on read files in java and write files in java to better understand the usage of BufferedReader and PrintWriter. The client program in this example publishes a message to the server and prints the message received from the server.
package com.sourcetricks.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class JavaClient {

  public static void main (String[] args) {
    
    Socket socket = null;
    try {
      socket = new Socket(InetAddress.getLocalHost().getHostName(), 8888);
      
      // Reader and writer
      BufferedReader reader = new BufferedReader
          (new InputStreamReader(socket.getInputStream()));
      PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

      // Write a message to server      
      writer.println("Hello from client");
      
      // Read message from server
      System.out.println(reader.readLine());      
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        socket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
Continue to read other Java tutorials from here.
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © StackStalk