Java nio file server

Java NIO — ServerSocket Channel

Java NIO server socket channel is again a selectable type channel used for stream oriented data flow connecting sockets.Server Socket channel can be created by invoking its static open() method,providing any pre-existing socket is not already present.Server Socket channel is created by invoking open method but not yet bound.In order to bound socket channel bind() method is to be called.

One point to be mentioned here is if channel is not bound and any I/O operation is tried to be attempted then NotYetBoundException is thrown by this channel.So one must be ensure that channel is bounded before performing any IO operation.

Incoming connections for the server socket channel are listen by calling the ServerSocketChannel.accept() method. When the accept() method returns, it returns a SocketChannel with an incoming connection. Thus, the accept() method blocks until an incoming connection arrives.If the channel is in non-blocking mode then accept method will immediately return null if there are no pending connections. Otherwise it will block indefinitely until a new connection is available or an I/O error occurs.

The new channel’s socket is initially unbound; it must be bound to a specific address via one of its socket’s bind methods before connections can be accepted.Also the new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object.

Like socket channel server socket channel could read data using read() method.Firstly the buffer is allocated. The data read from a ServerSocketChannel is stored into the buffer.Secondly we call the ServerSocketChannel.read() method and it reads the data from a ServerSocketChannel into a buffer. The integer value of the read() method returns how many bytes were written into the buffer

Similarly data could be written to server socket channel using write() method using buffer as a parameter.Commonly uses write method in a while loop as need to repeat the write() method until the Buffer has no further bytes available to write.

Important methods of Socket channel

  • bind(SocketAddress local) − This method is used to bind the socket channel to the local address which is provided as the parameter to this method.
  • accept() − This method is used to accepts a connection made to this channel’s socket.
  • connect(SocketAddress remote) − This method is used to connect the socket to the remote address.
  • finishConnect() − This method is used to finishes the process of connecting a socket channel.
  • getRemoteAddress() − This method return the address of remote location to which the channel’s socket is connected.
  • isConnected() − As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not.
  • open() − Open method is used open a socket channel for no specified address.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting server socket channel, passing it remote, and then returning that channel.
  • read(ByteBuffer dst) − This method is used to read data from the given buffer through socket channel.
  • setOption(SocketOption name, T value) − This method sets the value of a socket option.
  • socket() − This method retrieves a server socket associated with this channel.
  • validOps() − This method returns an operation set identifying this channel’s supported operations.Server-socket channels only support the accepting of new connections, so this method returns SelectionKey.OP_ACCEPT.
Читайте также:  Librosa play audio python

Example

The following example shows the how to send data from Java NIO ServerSocketChannel.

C:/Test/temp.txt

Client: SocketChannelClient.java

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 SocketChannelClient < public static void main(String[] args) throws IOException < ServerSocketChannel serverSocket = null; SocketChannel client = null; serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(9000)); client = serverSocket.accept(); System.out.println("Connection Set: " + client.getRemoteAddress()); Path path = Paths.get("C:/Test/temp1.txt"); FileChannel fileChannel = FileChannel.open(path, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE) ); ByteBuffer buffer = ByteBuffer.allocate(1024); while(client.read(buffer) >0) < buffer.flip(); fileChannel.write(buffer); buffer.clear(); >fileChannel.close(); System.out.println("File Received"); client.close(); > >

Output

Running the client will not print anything until server starts.

Server: SocketChannelServer.java

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 SocketChannelServer < public static void main(String[] args) throws IOException < SocketChannel server = SocketChannel.open(); SocketAddress socketAddr = new InetSocketAddress("localhost", 9000); server.connect(socketAddr); Path path = Paths.get("C:/Test/temp.txt"); FileChannel fileChannel = FileChannel.open(path); ByteBuffer buffer = ByteBuffer.allocate(1024); while(fileChannel.read(buffer) >0) < buffer.flip(); server.write(buffer); buffer.clear(); >fileChannel.close(); System.out.println("File Sent"); server.close(); > >

Output

Running the server will print the following.

Connection Set: /127.0.0.1:49558 File Received

Источник

Non-blocking Server in Java NIO

Java NIO (New Input/Output) is a very powerful networking and file-handling application that functions as an alternative to Java’s standard IO API. Due to the addition of more sophisticated features since JDK 4’s introduction, it has quickly emerged as the preferred I/O system among numerous engineers.

The improved support it offers for file handling and file system features is one of the features that distinguish Java NIO. Since the NIO file classes have such incredible capabilities, it is extensively used in file handling.

If you look closely, you’ll notice that java.nio package specifies the buffer classes employed by NIO APIs throughout. The best aspect is that it was created so that Java programmers could implement fast I/O without writing their native code.

Blocking vs Non Blocking I/O

Because of its use of Non-Blocking I/O, a Non-Blocking server can handle several requests simultaneously by the same process or thread. Consider a blocking process to be a queue at a ticket counter, wherein each customer must wait for the person in front to be serviced before proceeding.

In contrast, a non-blocking process is like a waiter at a restaurant who tries to serve all customers simultaneously by rotating through them and taking care of their orders.

Blocking servers work in a synchronous manner and complete each request before moving onto the next. This can result in longer wait times for clients, and multiple threads are required to serve each request, making it CPU-intensive. Non-blocking servers, on the other hand, use an asynchronous approach, allowing one thread to process several queries at the moment, reacting to each request as it finishes.

Читайте также:  Java stream integer to string

Features of Java NIO

Java NIO has some unique characteristics that set it apart from other IO systems. Here’s a rundown of the primary features of Java NIO −

  • Asynchronous and Non-Blocking IO − This feature allows for threads to perform other tasks while data is being read into a buffer. Instead of waiting for data to be fully loaded before processing begins, threads can continue their work while the data is being read.
  • Buffer-Oriented Approach − Java NIO stores data in a buffer, which allows for quick access and processing. When data is required, it is retrieved and processed from the buffer.

Algorithm

  • Step 1 − To begin with, we must import the necessary classes using the import statement.
  • Step 2 − Next, we need to create a public class named «WriteExample2.»
  • Step 3 − Inside this class, we must define a public static void main function that accepts String-type variable arguments.
  • Step 4 − Now, create a temporary file with the «.txt» extension by using the Files.createTempFile() method. To write, we can use the Files.write() method along with an iterable object holding the strings «Hello» and «world.»
  • Step 5 − To read every byte from the file defined by the Path object returned by the Files’ createTempFile() function, we can use the Files.readAllBytes() function. After that, we need to convert them to a String using the new String() constructor.
  • Step 6 − Lastly, print the String to the console using the System.out.println() method.

Example 1

This Java code creates a temporary text file and writes «Hello» and «world» to it. It then reads the file and prints its contents. The code uses the Files class from the Java NIO package to handle file operations.

package com.tutorialspoint.example.files; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; public class WriteExample2 < public static void main(String. args) throws IOException < Path path = Files.createTempFile("test-file", ".txt"); Iterableiterable = Arrays.asList("Hello", "world"); Files.write(path, iterable); byte[] bytes = Files.readAllBytes(path); System.out.println(new String(bytes)); > >

Output

Components of Java NIO

Java NIO is built on three fundamental components: Buffers, Channels, and Selectors. Here’s a brief overview of each −

  • Buffers − A buffer is a block of memory used to temporarily store data as it is being transferred from one location to another. In Java NIO, buffers are used to facilitate the reading and writing of data.
  • Channels − A channel in Java NIO represents a connection to objects that can perform IO operations, such as files and sockets. Channels are responsible for transmitting data between buffers and the objects they represent.
  • Selectors − A selector is a Java NIO component used to monitor one or more channels for events, such as readiness to perform an I/O operation. When a channel is ready, the selector can wake up and allow the appropriate thread to handle the operation.
Читайте также:  Javascript block select text

Non-Blocking Server Composition

Non-blocking servers are composed of a non-blocking IO pipeline, which is a chain of components that process both read and write IO operations in a non-blocking fashion. Here’s a breakdown of how this pipeline works −

  • A selector is used by each component in the pipeline to determine whether a channel has data to read.
  • When there is data, the component reads it and provides output based on it. After that, the output is written back to the channel.
  • Based on the component, non-blocking IO pipelines can read and write data as well as execute both operations.
  • The component begins reading data from the channel through the selector. Java NIO manages non-blocking IO operations, whereas selectors and selection keys with selectable channels define multiplexed IO operations.
  • Non-blocking IO pipelines divide data into logically ordered or combined messages alongside non-blocking data processing. This is comparable to using Java’s StreamTokenizer class to tokenize a stream of data before processing it.
  • Non-blocking models employ Java NIO selectors to check and give only those SelectableChannel instances that have data to read, as opposed to blocking IO pipelines, which use an interface similar to InputStream and only allow one byte to be read at a time.

Comparison of Blocking and Non-Blocking Models for Server Read/Write Operations

In the world of server architecture, the choice between using a blocking or non-blocking model for read and write operations can greatly impact the efficiency and scalability of a server.

A non-blocking model, in contrast to a blocking model, allows a process to accommodate numerous concurrent requests by interleaving non-blocking I/O calls.

To illustrate the difference between these models, let’s consider a hypothetical server that receives two requests. In a blocking model, the process must wait for request A to be fully processed before moving on to request B. In contrast, a non-blocking model can handle both requests simultaneously by interleaving the processing of requests A and B.

Java NIO enables a single thread to control numerous channels, supporting non-blocking I/O.

The channels that link a buffer and an object at the other end make asynchronous data transfer possible. Two classes, SocketChannel and ServerSocketChannel, implement the Java NIO channel and make it possible to receive and write data over TCP connections.

Server architects can create systems that are effective, scalable, and can manage numerous simultaneous requests by selecting the proper I/O model.

Conclusion

Java NIO provides a powerful networking and file-handling application with improved support for file handling and file system features. Its asynchronous and non-blocking I/O, buffer-oriented approach, and three fundamental components of buffers, channels, and selectors make it a unique I/O system.

The non-blocking server model of Java NIO is capable of handling multiple requests at the same time by using a non-blocking I/O pipeline. Unlike blocking IO pipelines, non-blocking models check and provide only those SelectableChannel instances that actually have data to read, making it a faster and more efficient system.

Источник

Оцените статью