package c.ct.io.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class ServerSocketChannelTest {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(80));
System.out.println("server is Listening client");
while (true) {
SocketChannel sc = serverSocketChannel.accept();
if (sc != null) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (sc.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
System.out.println();
buffer.clear();
}
}
}
// serverSocketChannel.close();
}
}
package c.ct.io.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SocketChannelTest {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for(int i=0;i<5;i++){
service.submit(new SocketThread("socketThread"+i));
}
service.shutdown();
}
private static class SocketThread implements Runnable{
private String name;
public SocketThread(String name) {
this.name = name;
}
@Override
public void run() {
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("localhost",80));
} catch (IOException e) {
e.printStackTrace();
}
String newData = this.name + " New String to write to file..." + System.currentTimeMillis();
ByteBuffer buffer = ByteBuffer.allocate(newData.length());
buffer.clear();
buffer.put(newData.getBytes());
buffer.flip();
while(buffer.hasRemaining()) {
try {
socketChannel.write(buffer);
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}