The latest slide deck about Java NIO.2 from *instinctools Java developer Alexandr Brui. You can find here Java NIO.2 design, work with data, selector & channels, reading & writing and many more.
Let's dive under the hood of Java network applications. We plan to have a deep look to classic sockets and NIO having live coding examples. Then we discuss performance problems of sockets and find out how NIO can help us to handle 10000+ connections in a single thread. And finally we learn how to build high load application server using Netty.
https://github.com/kslisenko/java-networking
Object-oriented programming Undergraduate Course Presentations
java.io streams and files in Java
University of Vale do Itajaí
Univali
Incremental Tecnologia
English version
Threads And Synchronization in C#
Concept about Threads And Synchronization in C#
it will help you about this concept
feel free
Download free programming applications on
http://www.androidapplications.xyz
Let's dive under the hood of Java network applications. We plan to have a deep look to classic sockets and NIO having live coding examples. Then we discuss performance problems of sockets and find out how NIO can help us to handle 10000+ connections in a single thread. And finally we learn how to build high load application server using Netty.
https://github.com/kslisenko/java-networking
Object-oriented programming Undergraduate Course Presentations
java.io streams and files in Java
University of Vale do Itajaí
Univali
Incremental Tecnologia
English version
Threads And Synchronization in C#
Concept about Threads And Synchronization in C#
it will help you about this concept
feel free
Download free programming applications on
http://www.androidapplications.xyz
This is all about socket programming in java using TCP and UDP socket and an example of simple Echo Server.
Also includes concepts of the socket, Socket class and methods and use of those.
The Loom project has been under work for many years, and just delivered Virtual Threads as a preview feature in the JDK 19. We now have a very precise idea of what they are and what you can do with them. Our good old Threads, created more than 25 years ago, will see a new kind of lightweight threads. This presentation shows you that creating a thread is easier and much cheaper, allowing the creation of millions of them in a single JVM. These virtual threads can be block at almost no cost. These new virtual threads bring with them new notions that will be covered in this talk. Loom threads are coming, and they will change the landscape of concurrent programming in Java.
This is all about socket programming in java using TCP and UDP socket and an example of simple Echo Server.
Also includes concepts of the socket, Socket class and methods and use of those.
The Loom project has been under work for many years, and just delivered Virtual Threads as a preview feature in the JDK 19. We now have a very precise idea of what they are and what you can do with them. Our good old Threads, created more than 25 years ago, will see a new kind of lightweight threads. This presentation shows you that creating a thread is easier and much cheaper, allowing the creation of millions of them in a single JVM. These virtual threads can be block at almost no cost. These new virtual threads bring with them new notions that will be covered in this talk. Loom threads are coming, and they will change the landscape of concurrent programming in Java.
IBM InterConnect: Java vs JavaScript for Enterprise WebAppsChris Bailey
The last few years have see a huge growth in the usage of JavaScript, to the extent that it is often reported to be the #1 programming language in use today. Additionally, the arrival of server-side JavaScript through frameworks such as Node.js and Ringo.js, and JavaScript on the JVM through Nashorn and Avatar.js, mean that enterprise web applications written in JavaScript are not just a possibility—but a reality for companies such as LinkedIn, eBay, Yahoo, ADP and Dow Jones. This session will compare and contrast the two platforms and describe the advantages of each for deploying, managing and monitoring highly scalable applications. It will also introduce IBM's strategy for building a common ecosystem around the two languages.
Presented at IBM InterConnect, Feb 25th, 2015
Apresentações para as disciplinas de Orientação a Objetos (graduação)
java.io fluxos (streams) e arquivos em Java
Universidade do Vale do Itajaí
Univali
Incremental Tecnologia
GDG Jakarta Meetup - Streaming Analytics With Apache BeamImre Nagi
Google slide version of this slide can be accessed from: https://docs.google.com/presentation/d/1Ws73JxlVH39HiKiYuF3vW903j8wFzxPQihXz4CQ_HZM/edit?usp=sharing
Node has captured the attention of early adopters by clearly differentiating itself as being asynchronous from the ground up while remaining accessible. Now that server side JavaScript is at the cutting edge of the asynchronous, real time web, it is in a much better position to establish itself as the go to language for also making synchronous, CRUD webapps and gain a stronger foothold on the server.
This talk covers the current state of server side JavaScript beyond Node. It introduces Common Node, a synchronous CommonJS compatibility layer using node-fibers which bridges the gap between the different platforms. We look into Common Node's internals, compare its performance to that of other implementations such as RingoJS and go through some ideal use cases.
forwarder.java.txt java forwarder class waits for an in.docxbudbarber38650
forwarder.java.txt
// java forwarder class
// waits for an inbound connection A on port INPORT
// when it is received, it launches a connection B to <OUTHOST,OUTPORT>
// and creates threads to read-B-write-A and read-A-write-B.
import java.net.*;
import java.io.*;
import java.util.*;
import java.text.*;
class forwarder {
public static String OUTHOST;
public static InetAddress OUTDEST;
public static short OUTPORT = 22;
public static short INPORT = 2345;
public static boolean DEBUG = true;
public static void main(String[] v) {
// get command-line parameters
if (v.length < 3) {
System.err.println("args: inport outhost outport");
return;
}
INPORT = (short)(new Integer(v[0])).intValue();
OUTHOST = v[1];
OUTPORT = (short)(new Integer(v[2])).intValue();
// DNS lookup, done just once!
System.err.print("Looking up address of " + OUTHOST + "...");
try {
OUTDEST = InetAddress.getByName(OUTHOST);
}
catch (UnknownHostException uhe) {
System.err.println("unknown host: " + OUTHOST);
return;
}
System.err.println(" got it!");
// initialize LISTENER socket
// wait for connection
ServerSocket ss = null;
ss = new ServerSocket(INPORT);// needs try-catch
Socket s1;
while(true) { // accept loop
s1 = ss.accept();// needs try-catch
// now set up the second connection from here to <OUTDEST,OUTPORT>,
// represented by a second socket s2
// Then create the two Copier instances, as described in the
// project description, and start() the two threads.
// At that point, this main loop simply continues
// by going back to the ss.accept() call.
} // accept loop
}// main
/**
* The Copier class handles unidirectional copying from one socket to another.
* You will need to create two of these in the main loop above,
* one for each direction. You create the Copier object, and then
* create and start a Thread object that runs that Copier.
* If c is your Copier instance (created with Copier c = new Copier(sock1, sock2)),
* then the thread is Thread t = new Thread(c), and you start the thread
* with t.start(). Or, in one step, (new Thread(c)).start()
*/
static class Copier implements Runnable {
private Socket _from;
private Socket _to;
public Copier (Socket from, Socket to) {
_from = from;
_to = to;
}
public void run() {
InputStream fis;
OutputStream tos;
try {
fis = _from.getInputStream();
tos = _to.getOutputStream();
} catch (IOException ioe) {
System.err.println("can't get IO streams from sockets");
return;
}
byte[] buf = new byte[2048];
int readsize;
while (true) {
try {
readsize = fis.read(buf);
} catch (IOException ioe) {
break;
}
if (readsize <= 0) break;
try {
tos.write(buf, 0, readsize);
} catch (IOException ioe) {
break;
}
}
// these should be safe close() calls!!
try {
fis.close();
tos.close();
_from.close();
_to.close();
} catch (IOException ioe) {
Syst.
The Presentation given at Guru Gobind Singh Polytechnic, Nashik for Third Year Information Technology and Computer Engineering Students on 08/02/2011.
Topic: Java Network Programming
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdf*instinctools
The Integration of #Odoo with leading data analysis tools allows combining the strengths and getting a powerful top for analyzing #data and making business decisions based on this data. We’ve gathered some of the advantages and disadvantages of data visualization integration in Odoo >
Examples of custom intuitive dashboards in Odoo.pdf*instinctools
Dashboards in #Odoo can change according to various tasks and purposes. With the help of BI tools, custom intuitive dashboards can be created for each decision-making level to meet business requirements and expectations >
As more offline businesses go digital, they need a scalable platform allowing them to process large volumes of data and enable effective #customersupport. Check out our new #casestudy to see how our web-based #CRM solution for the marketing department helped with #inventorymanagement and online bidding platform >
BI Technologies and ECM-System For A Multi-Industry Corporation*instinctools
Any delay or lack of coordination may entail tremendous losses and deadline shifts for a company with many interconnections. Check out a new #casestudy to see how our team improved the already implemented document workflow #software, providing such a company with an unblurred vision of work processes and the possibility to analyze personnel performance according to specific cross-sections! >
In a data-driven world, the more data is generated, the more critical it becomes for organizations to handle it properly. Some of this data is sensitive, which means that it must be protected from unauthorized access. Here are several recommendations from our data security expert on how to do it properly >
Traditional media concepts are a thing of the past. The entire industry is undergoing significant changes, and streaming services are no longer just platforms for consuming films and TV programs. We have prepared for you the most interesting facts about modern video streaming trends & technologies.
Happy Programmer's day | 2021 | *instinctools in numbers*instinctools
Every 256th day of the year, marking the number of distinct values that can be expressed with an eight-bit byte, we celebrate #programmersday. Here at *instinctools, we are proud to have such a great dedicated team and wish all engineers to keep their passion for coding and continue delivering the future. Now!
Happy Programmer's Day to all the innovative minds!
> instinctools.com
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...*instinctools
What problems can flexible and detailed analytics tackle in recruitment?
Here is the case study on data integration from Huntflow, a professional recruiting CRM system, with PowerBI software, that provided informative dashboards and helped:
✔️ Recruiters to get a clear picture of the talent pipeline, showing the path of every candidate from every source through every stage of the hiring process;
✔️ The company to fill the positions 21% faster than it used to;
✔️ C-levels to make the necessary adjustments to the wage scale.
Reach out to *instinctools Business Intelligence experts if you have a similar project idea or challenge with data integration > contact@instinctools.com
Top software development trends of 2021*instinctools
The technologies that businesses use today are bound to the new world paradigm and capable of adapting to it. Here are some trending technologies that can easily help companies adjust to a digital business world 2.0 in just a short time.
We know moving to the cloud may seem more costly than expected. Around 56% of IT decision-makers are facing challenges in maximizing long-term cloud cost savings (according to a Capita survey).
We described 6 issues to consider that may have an impact on your cloud migration project budget.
HRs and Teachers working in the Nostrum Oil & Gas company were experiencing problems in the process of the employees' training. There was a critical need for education process automation, creation of a platform for storing learning materials and giving all the employees with Azure credentials access at any time.
The final product developed by *instinctools provides staff members of the client's company with a single point of access to all educational materials. It allows Teachers and the HR Department to create courses, organize and store educational materials, as well as manage the process of learning.
The system provides Learners with remote access to the courses.
Unlike the current educational process, the final product generates reports required to comply with the state government.
P2P trading platform - Blockchain solution for electricity provider*instinctools
Innovations that matter! The idea of the Lition company was to develop a P2P trading platform for an open and direct energy exchange. It is now available for more than 41 million German households. Find live demo, project details and Lition's feedback in the slideshare document!
www.instinctools.com
Why everyone needs a business analyst on the IT project? Which responsibilities BA has? To make things clearer, we made this influential SlideShare for Business Analysts in IT.
Electron. Build cross platform desktop apps with web technologies!*instinctools
Distinct & accurate slide deck about Electron as a framework for creating native desktop applications from *instinctools frontend developer Andrew Zhemojtel.
Unique info about videostreaming compression in iOS from our the best iOS specialist Vladimir Predko. He's ready to answer all your questions! Go ahead!
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Understanding Nidhi Software Pricing: A Quick Guide 🌟
Choosing the right software is vital for Nidhi companies to streamline operations. Our latest presentation covers Nidhi software pricing, key factors, costs, and negotiation tips.
📊 What You’ll Learn:
Key factors influencing Nidhi software price
Understanding the true cost beyond the initial price
Tips for negotiating the best deal
Affordable and customizable pricing options with Vector Nidhi Software
🔗 Learn more at: www.vectornidhisoftware.com/software-for-nidhi-company/
#NidhiSoftwarePrice #NidhiSoftware #VectorNidhi
In the ever-evolving landscape of technology, enterprise software development is undergoing a significant transformation. Traditional coding methods are being challenged by innovative no-code solutions, which promise to streamline and democratize the software development process.
This shift is particularly impactful for enterprises, which require robust, scalable, and efficient software to manage their operations. In this article, we will explore the various facets of enterprise software development with no-code solutions, examining their benefits, challenges, and the future potential they hold.
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
AI Genie Review: World’s First Open AI WordPress Website CreatorGoogle
AI Genie Review: World’s First Open AI WordPress Website Creator
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-genie-review
AI Genie Review: Key Features
✅Creates Limitless Real-Time Unique Content, auto-publishing Posts, Pages & Images directly from Chat GPT & Open AI on WordPress in any Niche
✅First & Only Google Bard Approved Software That Publishes 100% Original, SEO Friendly Content using Open AI
✅Publish Automated Posts and Pages using AI Genie directly on Your website
✅50 DFY Websites Included Without Adding Any Images, Content Or Doing Anything Yourself
✅Integrated Chat GPT Bot gives Instant Answers on Your Website to Visitors
✅Just Enter the title, and your Content for Pages and Posts will be ready on your website
✅Automatically insert visually appealing images into posts based on keywords and titles.
✅Choose the temperature of the content and control its randomness.
✅Control the length of the content to be generated.
✅Never Worry About Paying Huge Money Monthly To Top Content Creation Platforms
✅100% Easy-to-Use, Newbie-Friendly Technology
✅30-Days Money-Back Guarantee
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIGenieApp #AIGenieBonus #AIGenieBonuses #AIGenieDemo #AIGenieDownload #AIGenieLegit #AIGenieLiveDemo #AIGenieOTO #AIGeniePreview #AIGenieReview #AIGenieReviewandBonus #AIGenieScamorLegit #AIGenieSoftware #AIGenieUpgrades #AIGenieUpsells #HowDoesAlGenie #HowtoBuyAIGenie #HowtoMakeMoneywithAIGenie #MakeMoneyOnline #MakeMoneywithAIGenie
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
2. Network socket
Network socket is an endpoint of a connection across a computer network.
Main types of Internet socket:
● Datagram sockets, which use User Datagram Protocol (UDP).
● Stream sockets, which use Transmission Control Protocol (TCP) or Stream
Control Transmission Protocol (SCTP).
● Raw sockets, typically available in routers and other network equipment.
4. Java.IO - Stream-oriented
Data Source Program
Data
Destination Program
001001001111001001001001011
001001001111001001001001011
5. Java.IO - Blocking I/O
Socket Thread
read data, block until ready
read data, block until ready
write data, block until ready
write data, block until ready
6. Java.IO — Work with data
// read from socket
Scanner sc = new Scanner(socket.getInputStream());
String string = sc.nextLine();
System.out.println("Received " + string);
// write to socket
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println("Hello");
7. Java.NIO — Buffer-oriented & Non-blocking I/O
Channel Buffer Thread
read data into buffer
fill data into buffer
check data in buffer
goto top
8. Java.NIO — Work with data
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
// prepare to read
readBuffer.clear();
SocketChannel channel = getChannel();
channel.read(readBuffer);
readBuffer.flip();
// reading the buffer
// ...............…
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
// prepare to put data
writeBuffer.clear();
// putting the data
// ...............
// prepare to write
writeBuffer.flip();
channel.write(writeBuffer);
9. Java.NIO — Selector & Channels
Channel is a lightweight entity effeciently
transporting data between sockets as a tube.
Selector is a manager allowing a single thread to
monitor multiple input channels.
10. Java.IO - Classic IO server design
Server
Socket
Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
12. Java.NIO — NIO server design
ServerSocketChannel channel = ServerSocketChannel.open();
channel.bind(new InetSocketAddress("localhost", 2222));
channel.configureBlocking(false);
Selector selector = Selector.open();
SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
if (selector.select() == 0) {
Thread.sleep(1);
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey selectionKey = keyIterator.next();
if (selectionKey.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (selectionKey.isConnectable()) {
// a connection was established with a remote.
} else if (selectionKey.isReadable()) {
// a channel is ready for reading
} else if (selectionKey.isWritable()) {
// a channel is ready for writing
}
keyIterator.remove();
}
}
14. Java.NIO.2 — Reading
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
// prepare to read
readBuffer.clear();
AsynchronousSocketChannel channel = getChannel2();
channel.read(readBuffer, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
// buffer is ready for read
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
15. Java.NIO.2 — Writing
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
// prepare to put data
writeBuffer.clear();
// putting data
// ...............
// prepare to write
writeBuffer.flip();
AsynchronousSocketChannel channel = getChannel2();
channel.write(writeBuffer, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
// writing has been completed
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
16. Java.NIO — NIO.1 server design
ServerSocketChannel channel = ServerSocketChannel.open();
channel.bind(new InetSocketAddress("localhost", 2222));
channel.configureBlocking(false);
Selector selector = Selector.open();
SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
if (selector.select() == 0) {
Thread.sleep(1);
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey selectionKey = keyIterator.next();
if (selectionKey.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (selectionKey.isConnectable()) {
// a connection was established with a remote.
} else if (selectionKey.isReadable()) {
// a channel is ready for reading
} else if (selectionKey.isWritable()) {
// a channel is ready for writing
}
keyIterator.remove();
}
}
17. Java.NIO — NIO.2 server design
AsynchronousChannelGroup group =
AsynchronousChannelGroup.withThreadPool(newFixedThreadPool(10));
AsynchronousServerSocketChannel channel = open(group);
channel.bind(new InetSocketAddress("localhost", 2222));
channel.accept(null, toHandler((client, attach) -> {
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
client.read(readBuffer, null, toHandler((result, attachment) -> {
// buffer is ready for read
}));
client.write(writeBuffer, null, toHandler((result, attachment) -> {
// writing has been completed
}));
}));
18. public class NetworkServer {
AsynchronousServerSocketChannel channel;
CompletionHandler<AsynchronousSocketChannel, Void> handler;
public NetworkServer(SocketAddress address) throws IOException {
AsynchronousChannelGroup group = withFixedThreadPool(10, Thread::new);
handler = toHandler((channel, attach) -> processAccept(channel));
channel = AsynchronousServerSocketChannel.open(group);
channel.bind(address);
channel.accept(null, toHandler((clientChannel, attach) -> processAccept(clientChannel)));
}
private void processAccept(AsynchronousSocketChannel clientChannel) {
NetworkClient networkClient = new NetworkClient(clientChannel, message ->
out.println("Server: received: " + message));
networkClient.write("Hello! I'm NIO.2 server!n");
channel.accept(null, handler);
}
public void stop() throws IOException {
channel.close();
}
}
Java NIO.2 — Basic implementation of server