Day: 5 March 2011

Node JS and Server side Java Script

Let's start right at the beginning. Bear with me, it might get long... The following snippet of Java code could be used to create a server which receives TCP/IP requests: class Server implements Runnable { public void run() { try { ServerSocket ss = new ServerSocket(PORT); while (!Thread.interrupted()) Socket s = ss.accept(); s.getInputStream(); //read from this s.getOutputStream(); //write to this } catch (IOException ex) { /* ... */ } } } This code runs as far as the line with ss.accept(), which blocks until an incoming request is received. The accept method then returns and you have access to the input and output streams in order to communicate with the client. There is one issue with this code. Think about multiple requests coming in at the same time. You are dedicated to completing the first request before making the next call to the accept method. Why? Because the accept method blocks. If you decided you would read a chunk off the input stream of the first connection, and then be kind to the next connection and accept it and handle its first chunk before continuing with the original (first) connection, you would have a problem, because the accept method blocks. If there were no second request, you wouldn't be able to finish off the first request, because the JVM blocks on that accept method. So, you must handle an incoming request in its entirety, before accepting a second incoming request. This isn't so bad, because you can create the ServerSocket…

Read more