Home » Core Java » nio » Java Nio SocketChannel Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Java Nio SocketChannel Example

SocketChannel is a selectable channel belonging to the java.nio.channels package and is used for reading or writing the stream-oriented data. In this tutorial, we learn how to use the SocketChannel and how it is used for reading or writing the stream-oriented data by using the TCP based protocol.
 
 
 
 
 
 
 

1. Introduction

Java Nio was developed to allow the Java programmers implement the high-speed input-output operations without using the custom native code. Nio moves the time-taking I/O activities like filling, namely and draining buffers etc back into the operating system, thus allows the great increase in the operational speed.

1.1 Java Nio Components

The Java Nio classes are contained in the java.nio package and it is important to understand that the Nio subsystem does not replace the existing stream-based I/O classes available in java.io package. The important Nio classes are grouped under different categories that are shown below:

Fig. 1: Nio Components

Fig. 1: Nio Components

Let us understand the important classes contained in these groups.

PackagePurpose
java.nioIt is a top-level package for NIO system. The various types of buffers are encapsulated by this NIO system.
java.nio.charsetIt encapsulates the character sets and also supports the encoding and the decoding operation that converts the characters to bytes and bytes to characters.
java.nio.charset.spiIt supports the service provider for the character sets.
java.nio.channelsIt supports the channel which is essentially open for the I/O connections.
java.nio.channels.spiIt supports the service providers for the channels.
java.nio.fileIt provides the support for the files.
java.nio.file.spiIt supports the service providers for the file system.
java.nio.file.attributeIt provides the support for the file attributes.

1.2 Java Nio Channels

In Java Nio, Channels are used for the input-output transfers. A channel is like a tube that transports the data between a buffer and an entity at the other end. A channel reads the data from an entity and places it in the buffer blocks for consumption. The developers then write the data to the buffer blocks so that it can be transported by the channel to the other end.

Channels are the gateway provided by the Java Nio package to access the native input-output mechanism. Developers should use buffers to interact with the channels and to perform the input-output operations where these buffers act as the endpoints provided by the channels to send and receive the data.

Fig. 2: Nio Channels

Fig. 2: Nio Channels

1.2.1 Channel Characteristics

  • Unlike streams, channels are two-way in nature and can perform both, read and write operations
  • A channel reads the data into a buffer and writes the data from a buffer
  • A channel can even perform the asynchronous read and write operations
  • A non-blocking channel does not put the invoking thread in the sleep mode
  • Stream-oriented channels like sockets can only be placed in the non-blocking mode
  • The data can be transferred from one channel to another if any one of the channels is a FileChannel

1.2.2 Channel Classes

Below are the two major types of channel classes provided as an implementation in the Java Nio package:

  • FileChannel: These are the File-based read/write channels that cannot be placed in a non-blocking mode
  • SocketChannel: The Java Nio Socket Channel is used for connecting a channel with a TCP network socket. It is equivalent to the Java Networking Sockets used in the network programming. There are two methods available in the Java Nio package for creating a SocketChannel i.e. ServerSocketChannel and the DatagramChannel. Do note, SocketChannel are the selectable channels that can easily operate in the non-blocking mode

Now, open up the Eclipse IDE and let’s see how to implement the socket channel with Java Nio package!

2. Java Nio Socket Channel Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Java Nio Socket Channel Project Structure

Fig. 3: Java Nio Socket Channel Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 4: Create Maven Project

Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 5: Project Details

Fig. 5: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters

Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JavaNioSocketChannel</groupId>
	<artifactId>JavaNioSocketChannel</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want like JUnit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 7: Java Package Creation

Fig. 7: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java.nio.

Fig. 8: Java Package Name (com.jcg.java.nio)

Fig. 8: Java Package Name (com.jcg.java.nio)

Once the package is created in the application, we will need to create the implementation classes. Right-click on the newly created package: New -> Class.

Fig. 9: Java Class Creation

Fig. 9: Java Class Creation

A new pop window will open and enter the file name as: FileReceiver. The receiver class will be created inside the package: com.jcg.java.nio.

Fig. 10: Java Class (FileReceiver.java)

Fig. 10: Java Class (FileReceiver.java)

Repeat the step (i.e. Fig. 9) and enter the filename as FileSender. The sender class will be created inside the package: com.jcg.java.nio.

Fig. 11: Java Class (FileSender.java)

Fig. 11: Java Class (FileSender.java)

3.1.1 Implementation of Receiver Class

The receiver class is used to receive the file from an entity (i.e. read from the socket channel). Add the following code to it:

FileReceiver.java

package com.jcg.java.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

public class FileReceiver {

	public static void main(String[] args) throws IOException {
		FileReceiver server = new FileReceiver();
		SocketChannel socketChannel = server.createServerSocketChannel();
		server.readFromSocketChannel(socketChannel);
	}

	private void readFromSocketChannel(SocketChannel socketChannel) throws IOException {
		// Receiver File Location
		String filePath ="receivedConfig/sample.txt";

		Path path = Paths.get(filePath);
		FileChannel fileChannel = FileChannel.open(path, 
				EnumSet.of(StandardOpenOption.CREATE, 
						StandardOpenOption.TRUNCATE_EXISTING,
						StandardOpenOption.WRITE)
				);		

		// Allocate a ByteBuffer
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while(socketChannel.read(buffer) > 0) {
			buffer.flip();
			fileChannel.write(buffer);
			buffer.clear();
		}
		fileChannel.close();
		System.out.println("Received File Successfully!");
		socketChannel.close();
	}

	private SocketChannel createServerSocketChannel() throws IOException {
		ServerSocketChannel serverSocket = null;
		SocketChannel client = null;
		serverSocket = ServerSocketChannel.open();
		serverSocket.socket().bind(new InetSocketAddress(9000));
		client = serverSocket.accept();

		System.out.println("Connection Established . .?= " + client.getRemoteAddress());
		return client;
	}
}

3.1.2 Implementation of Sender Class

The sender class is used to read the file from a disk and send it across the socket channel so that it can be received by an entity present at the other end. Add the following code to it:

FileSender.java

package com.jcg.java.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileSender {

	public static void main(String[] args) throws IOException {
		FileSender client = new FileSender();
		SocketChannel socketChannel = client.createChannel();
		client.sendFile(socketChannel);
	}

	private void sendFile(SocketChannel socketChannel) throws IOException {		
		// Sender File Location
		String filePath ="senderConfig/sample.txt";

		// Read a File From Disk. It's Filesize Is 1KB
		Path path = Paths.get(filePath);
		FileChannel inChannel = FileChannel.open(path);

		// Allocate a ByteBuffer
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while(inChannel.read(buffer) > 0) {
			buffer.flip();
			socketChannel.write(buffer);
			buffer.clear();
		}
		socketChannel.close();
	}

	private SocketChannel createChannel() throws IOException {
		SocketChannel socketChannel = SocketChannel.open();
		SocketAddress socketAddr = new InetSocketAddress("localhost", 9000);
		socketChannel.connect(socketAddr);
		return socketChannel;
	}
}

4. Run the Application

To run the Java Nio application, Right-click on the FileReceiver class -> Run As -> Java Application. Follow the similar step and execute the FileSender class. Developers can debug the example and see what happens after every step!

Fig. 12: Run Application

Fig. 12: Run Application

5. Project Demo

When developers run the above program, the new file will be written in the project’s receivedConfig/ directory and the code shows the following status as output.

Fig. 13: Receiver Output

Fig. 13: Receiver Output

That’s all for this post. Happy Learning!!

6. Conclusion

This tutorial uses a simple example to illustrate SocketChannel’s functionality and helps developers understand the basic configuration required to achieve this operation. That’s all for this tutorial and I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Java Nio for the beginners.

Download
You can download the full source code of this example here: JavaNioSocketChannel
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of