• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

How to use Socket API for creating Client-Server application in Java

August 20, 2012 //  by Mohamed Sanaulla//  Leave a Comment

In this example we make use of ServerSocketChannel and SocketChannel to create a simple Echo application where in the Server would print the data sent by the client.

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

The code is explained with the required comments:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * This creates a server on a particular IP address and the port.
 *
 */
public class ServerClass {

  public static void main(String[] args) {

    // Create a Server socket channel.
    try (ServerSocketChannel serverSocket = ServerSocketChannel.open()) {

      // Bind the server socket channel to the IP address and Port
      serverSocket.bind(new InetSocketAddress("127.0.0.1", 6667));
      System.out.println("Waiting for client connections");

      while (true) {
        
        //Wait and Accept the client socket connection. 
        try (SocketChannel socketChannel = serverSocket.accept()) {
          
          //Printing the address of the client.
          System.out.println("Obtained connection from: "+socketChannel.getRemoteAddress().toString());
          
          //Creating a reader for reading the content on the socket input stream.
          Scanner socketReader = new Scanner(socketChannel.socket().getInputStream());
          while(socketReader.hasNext()){
            
            //Reading the content of the socket input stream.
            System.out.println(socketReader.nextLine());
            
          }

        } catch(IOException ex){
          ex.printStackTrace();
        }
      }

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

}

and the client which connects to the server is:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

public class CilentClass {
  
  public static void main(String[] args) {
    
    //Create a client socket.
    try(SocketChannel socketChannel = SocketChannel.open()){
      
      //Bind the client socket to the server socket.
      socketChannel.connect(new InetSocketAddress("127.0.0.1", 6667));
      
      //Writing to the socket channel.
      PrintWriter writer = new PrintWriter(socketChannel.socket().getOutputStream(), true);
      writer.println("Client sending instruction 1");
      writer.println("Client sending instruction 2");
      writer.println("Client sending instruction 3");
      writer.println("Client sending instruction 4");
      
    }catch(IOException ex){
      ex.printStackTrace();
    }
    
  }
}

Category: JavaTag: Core Java

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Previous Post: « How to use ByteBuffer in Java?
Next Post: Reading file asynchronously in Java »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact