Using SocketChannel sc =(SocketChannel)key.channel();, we can extract data from the port to the buffer.
To continuously receive data from a port without data loss, what should the code look like?
Here is my code
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
public class MultiPortEcho
{
private int ports[];
private ByteBuffer echoBuffer = ByteBuffer.allocate(32000);
public MultiPortEcho( int ports[] ) throws IOException
{
this.ports = ports;
go();
}
private void go() throws IOException
{
Selector selector = Selector.open();
for (int i=0; i<ports.length; ++i)
{
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking( false );
ServerSocket ss = ssc.socket();
InetSocketAddress address = new InetSocketAddress( ports[i] );
ss.bind( address );
SelectionKey key = ssc.register( selector, SelectionKey.OP_ACCEPT );
System.out.println( "Going to listen on "+ports[i] );
}
while (true)
{
int num = selector.select();
System.out.println("num::::"+num);
Set selectedKeys = selector.selectedKeys();
Iterator it = selectedKeys.iterator();
while (it.hasNext())
{
SelectionKey key = (SelectionKey)it.next();
if ((key.readyOps() & SelectionKey.OP_ACCEPT)== SelectionKey.OP_ACCEPT)
{
ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking( false );
SelectionKey newKey = sc.register(selector,SelectionKey.OP_READ);
it.remove();
System.out.println( "Got connection from "+sc );
}
else if ((key.readyOps() & SelectionKey.OP_READ)== SelectionKey.OP_READ)
{
SocketChannel sc =(SocketChannel)key.channel();
System.out.println("sc::::"+sc);
int bytesEchoed = 0;
{
echoBuffer.clear();
int r = sc.read(echoBuffer);
System.out.println("r:::" + r);
if (r == -1)
{
echoBuffer.rewind();
byte[] array = new byte[100000];
while (echoBuffer.hasRemaining())
{
int n = echoBuffer.remaining();
System.out.println("size:" + n);
echoBuffer.get(array,0,n );
System.out.println(new String(array,0,n));
key.cancel();
it.remove();
}
}
}
}
}
}
}
static public void main( String args[] ) throws Exception
{
FileOutputStream fileoutputstream = new FileOutputStream("MultiPort.txt", false);
PrintStream printstream = new PrintStream(fileoutputstream);
System.setOut(printstream);
if (args.length<=0) {
System.err.println( "Usage: java MultiPortEcho port [port port ...]" );
System.exit( 1 );
}
int ports[] = new int[args.length];
for (int i=0; i<args.length; ++i) {
ports[i] = Integer.parseInt( args[i] );
}
new MultiPortEcho( ports );
}
}
Rajeev
source
share