Beginning Java 8 APIs, Extensions and Libraries: Swing, JavaFX, JavaScript, JDBC and Network Programming APIs by Kishori Sharan
Author:Kishori Sharan [Sharan, Kishori]
Language: eng
Format: epub, pdf
Tags: Object Oriented, Java, Computers, Programming, Programming Languages
ISBN: 9781430266624
Google: NYKMBAAAQBAJ
Publisher: Apress
Published: 2014-09-15T20:44:30+00:00
Setting up an Asynchronous Client Socket Channel
An instance of the AsynchronousSocketChannel class is used as an asynchronous client socket channel in a client application. The static open() method of the AsynchronousSocketChannel class returns an open channel of the AsynchronousSocketChannel type that is not yet connected to a server socket channel. The channel’s connect() method is used to connect to a server socket channel. The following snippet of code shows how to create an asynchronous client socket channel and connect it to a server socket channel. It uses a Future object to handle the completion of the connection to the server.
// Create an asynchronous socket channel
AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
// Connect the channel to the server
String serverName = "localhost";
int serverPort = 8989;
SocketAddress serverAddr = new InetSocketAddress(serverName, serverPort);
Future<Void> result = channel.connect(serverAddr);
System.out.println("Connecting to the server...");
// Wait for the connection to complete
result.get();
// Connection to the server is complete now
System.out.println("Connected to the server...");
Once the client socket channel is connected to a server, you can start reading from the server and writing to the server using the channel’s read() and write() methods asynchronously. Both methods let you handle the completion of the operation using a Future object or a CompletionHandler object. You will use an Attachment class as shown to pass the context to the completion handler:
class Attachment {
AsynchronousSocketChannel channel;
ByteBuffer buffer;
Thread mainThread;
boolean isRead;
}
In the class, the channel instance variable holds the reference to the client channel. The buffer instance variable holds the reference to the data buffer. You will use the same data buffer for reading and writing. The mainThread instance variable holds the reference to the main thread of the application. When the client channel is done, you can interrupt the waiting main thread, so the client application terminates. The isRead instance variable indicates if the operation is a read or a write. If it is true, it means it is a read operation. Otherwise, it is a write operation.
Listing 5-17 contains the complete code for an asynchronous client socket channel. It uses two inner classes called Attachment and . An instance of the Attachment class is used as an attachment to the read() and write() asynchronous operations. An instance of the ReadWriteHandler class is used as a completion handler for the read() and write() operations. Its getTextFromUser() method prompts the user to enter a message on the standard input and returns the user-entered message. The completed() method of the completion handler checks if it is a read or a write operation. If it is a read operation, it prints the text that was read from the server on the standard output. It prompts the user for another message. If the user enters Bye, it terminates the application by interrupting the waiting main thread. Note that the channel is closed automatically when the program exits the try block because it is opened inside a try-with-resources block in the main() method.
Listing 5-17. An Asynchronous Client Socket Channel
// AsyncEchoClientSocket.java
package com.jdojo.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.concurrent.Future;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.nio.channels.AsynchronousSocketChannel;
public class AsyncEchoClientSocket {
private static class Attachment {
AsynchronousSocketChannel
Download
Beginning Java 8 APIs, Extensions and Libraries: Swing, JavaFX, JavaScript, JDBC and Network Programming APIs by Kishori Sharan.pdf
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Deep Learning with Python by François Chollet(12568)
Hello! Python by Anthony Briggs(9912)
OCA Java SE 8 Programmer I Certification Guide by Mala Gupta(9795)
The Mikado Method by Ola Ellnestam Daniel Brolund(9777)
Dependency Injection in .NET by Mark Seemann(9337)
Algorithms of the Intelligent Web by Haralambos Marmanis;Dmitry Babenko(8295)
Test-Driven iOS Development with Swift 4 by Dominik Hauser(7762)
Grails in Action by Glen Smith Peter Ledbrook(7696)
The Well-Grounded Java Developer by Benjamin J. Evans Martijn Verburg(7557)
Becoming a Dynamics 365 Finance and Supply Chain Solution Architect by Brent Dawson(7050)
Microservices with Go by Alexander Shuiskov(6816)
Practical Design Patterns for Java Developers by Miroslav Wengner(6728)
Test Automation Engineering Handbook by Manikandan Sambamurthy(6674)
Secrets of the JavaScript Ninja by John Resig Bear Bibeault(6409)
Angular Projects - Third Edition by Aristeidis Bampakos(6078)
The Art of Crafting User Stories by The Art of Crafting User Stories(5607)
NetSuite for Consultants - Second Edition by Peter Ries(5545)
Demystifying Cryptography with OpenSSL 3.0 by Alexei Khlebnikov(5346)
Kotlin in Action by Dmitry Jemerov(5062)
