Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

NIO non-blocking newbie  RSS feed

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was reading about the non-blacking IO and ran into the nio classes. I am still a bit confused by it.

I started off with learning the EchoServlet that floats around on the net, but I am not sure how to make it non-blocking. I do understand the EchoServlet though

Any good resources someone can point me to.

import java.io.*;
import java.net.*;

public class EchoServer
{
private static final int port = 8080;

public static void main(String args[])
{
ServerSocket serverSocket = null;
String input;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;

try
{
serverSocket = new ServerSocket(port);
}
catch (Exception e)
{
//Ideally a better message
e.printStackTrace();
}

while (true)
{
try
{
//Single Treaded
System.out.println("EchoServer started. Now accepting connections.");
clientSocket = serverSocket.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());

while (true)
{
input = is.readLine();
//Use StringBuffer's reverse method
StringBuffer inputBuffer = new StringBuffer(input);
StringBuffer reversedInput = inputBuffer.reverse();
os.println(reversedInput.toString());
}
}
catch (IOException e)
{
//Ideally a better message
System.out.println(e);
}
}
}
}
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at the Non-Blocking Time Server Example from the JDK release notes.
Since it is a very specialized area, there's not a lot of support, either in the way of documentation or community, for NIO. If you need to master it, I recommend getting a book.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!