CS计算机代考程序代写 Java package nbtcpserver;

package nbtcpserver;

import java.io.IOException;
import java.nio.channels.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NBTCPServer {

public AsynchronousServerSocketChannel asyncServerSocketChannel;
final ByteBuffer myBuffer;

public NBTCPServer() throws Exception {

// allocate a ByteBuffer object that will be used for reading and writing data from and to the socket, respectively
myBuffer = ByteBuffer.allocate(2048);

//create an asynchronous socket channel and bind it to port 10000 (where the server listens for new connections)
asyncServerSocketChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(10000));
asyncServerSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

// the following call is non-blocking – it returns a Future instance – its result is of type AsynchronousSocketChannel (Java Generics are used here) – i.e. the socket channel to communicate with the client
Future acceptFuture = asyncServerSocketChannel.accept();

// uncomment the following (and in the rest of the code) to understand how a single ByteBuffer is used for this connection
// important fields include: capacity, limit, position
// important methods: flip, clear
// reference:
// http://docs.oracle.com/javase/7/docs/api/java/nio/Buffer.html
// http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html

// System.out.println(“capacity: ” + myBuffer.capacity());
// System.out.println(“limit : ” + myBuffer.limit());
// System.out.println(“position : ” + myBuffer.position());

// define a completion handler which will be called when some data is read (the assumption in this program is that read will always read all the data from the client)
// reference:
// http://docs.oracle.com/javase/7/docs/api/java/nio/channels/AsynchronousSocketChannel.html
// http://docs.oracle.com/javase/7/docs/api/java/nio/channels/CompletionHandler.html

try (
// the following call (get()) on the future object will block
// One could poll the future instance using the isDone() method in some other thread but let’s just block here
// Alternatively a CompletionHandler could be asynchronously called in a separate thread managed by NIO.2 (that’s what we do for reading and writing data from and to the socket, respectively, later on)
AsynchronousSocketChannel worker = acceptFuture.get()) {
// uncomment the following (and in the rest of the code) to understand how a single ByteBuffer is used for this connection
// important fields include: capcaity, limit, position
// important methods: flip, clear
// reference:
// http://docs.oracle.com/javase/7/docs/api/java/nio/Buffer.html
// http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html

// System.out.println(“capacity: ” + myBuffer.capacity());
// System.out.println(“limit : ” + myBuffer.limit());
// System.out.println(“position : ” + myBuffer.position());

// define a completion handler which will be called when some data is read (the assumption in this program is that read will always read all the data from the client)
// reference:
// http://docs.oracle.com/javase/7/docs/api/java/nio/channels/AsynchronousSocketChannel.html
// http://docs.oracle.com/javase/7/docs/api/java/nio/channels/CompletionHandler.html

final CompletionHandler readCompletionHandler = new CompletionHandler() {

@Override
public void completed(Integer result, CompletionHandler handler) {

// within this inner class object (i.e. readCompletionHandler) we define another one
// This handler will handle write completions – when some data is written (again the assumption is that everything is written when the completed method is called)
final CompletionHandler writeCompletionHandler = new CompletionHandler() {

@Override
public void completed(Integer result, CompletionHandler handler) {
System.out.println(“Wrote ” + result + ” bytes”);

// System.out.println(“capacity: ” + myBuffer.capacity());
// System.out.println(“limit : ” + myBuffer.limit());
// System.out.println(“position : ” + myBuffer.position());

// clear the buffer
// clear() makes a buffer ready for a new sequence of channel-read or relative put operations: It sets the limit to the capacity and the position to zero.
myBuffer.clear();

// System.out.println(“Cleared buffer”);

// System.out.println(“capacity: ” + myBuffer.capacity());
// System.out.println(“limit : ” + myBuffer.limit());
// System.out.println(“position : ” + myBuffer.position());

// after data is echoed back to the client, read again with the same read handler (which is passed as an attachment)

worker.read(myBuffer, handler, handler);
}

@Override
public void failed(Throwable exc, CompletionHandler handler) {
System.err.println(“Probably the connected process died. closing socket and exiting….”);
try {
worker.close();
} catch (IOException ex) {
Logger.getLogger(NBTCPServer.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(0);
}
};

if (result == -1) {
System.err.println(“Socket closed on the other side!!”);
try {
worker.close();
} catch (IOException ex) {
Logger.getLogger(NBTCPServer.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(0);
}
System.out.println(“Just Read ” + result + ” bytes asynchronously!!”);

// System.out.println(“capacity: ” + myBuffer.capacity());
// System.out.println(“limit : ” + myBuffer.limit());
// System.out.println(“position : ” + myBuffer.position());

// flip the buffer
// flip() makes a buffer ready for a new sequence of channel-write or relative get operations: It sets the limit to the current position and then sets the position to zero.

myBuffer.flip();

// System.out.println(“Flipped buffer”);

// System.out.println(“capacity: ” + myBuffer.capacity());
// System.out.println(“limit : ” + myBuffer.limit());
// System.out.println(“position : ” + myBuffer.position());

// write the data to the client – the buffer is previously flipped so everything should work ok
worker.write(myBuffer, handler, writeCompletionHandler);
}

@Override
public void failed(Throwable exc, CompletionHandler handler) {
System.err.println(“Probably the connected process died. closing socket and exiting….”);

try {
worker.close();
} catch (IOException ex) {
Logger.getLogger(NBTCPServer.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(0);
}

};

//I will try to read – this method will not block!! – I register a completion handler – its completed (or failed) method will be called when I read some data
worker.read(myBuffer, readCompletionHandler, readCompletionHandler);
// wait for a very long time (basically until System.exit(0); is called by a completion handler)
Thread.sleep(Long.MAX_VALUE);
}
}

public static void main(String[] args) throws Exception {
NBTCPServer nbtcpServer = new NBTCPServer();
}
}