Sie sind auf Seite 1von 6

Clase ServerSocketChannel(java.nio.channels.

ServerSocketChannel)
Opciones Configurables:

SO_RCVBUF ->Tamao de buffer


SO_RESUSEADOR ->Reutilizar direccin

Constructor

Protected ServerSocketChannel(SerlectorProvider p)

Mtodos

Abstract SocketChannel accept()


ServerSocketChannel bind(SocketAddress local)
Abstract ServerSocketChannel bind(SocketAddress local,int backlog)>Sirve para asignar el socket
Static ServerSocketChannel open()
Abstract <T>ServerSocketChannel setOption(SocketOption<T>op,T val)>Modificar socket
SelectionKey Register(Selector sel,in top)
Abstract SelectableChannel configureBlocking(boolean b)

Creacion del Socket Servidor


Try{
ServerSocketChannel s=ServerSocketChannel.open();
s.configureBlocking(false);
InetSocketAddress local=new InetSocketAddress(1234);
s.socket()bind(local);
s.setOption(StandarSocketOption.SO_REUSADOR,true);
Selector sel=Selector.open();
s.register(sel,SelectionKey.OP_ACCEPT);
System.out.println(Servidor iniciadoesperando clientes);
for(;;){
sel.select();->Indica si hay algo que procesarse :v
Iterator<SelectionKet>it = sel.selectedKeys().iterator();>SelectionKey indica una
conexin de entrada y salida
While(it.hasNext()){
SelectionKey h=(SelectionKey) it.next();

It.remove()
If(h.isAcceptable()){
SocketChannel cl=s.accept();
System.out.println(Cliente conectado
desde+cl.socket().getInetAddress()
+;+cl.socket().getPort());
cl.configureBlocking(false);
cl..register(sel,SelectionKey.OP_READ|
SelectomKet.OP_WRITE)
continue;
}
If(k.isReadable()){
SocketChannel ch=(SocketChannel)k.channel();
->Referencia del socket
ByteBuffer b=ByteBuffer.allocateDirect(2000);
Int n= ch.read(b);
System.out.println(Se leyeron+n+bytes);
b.flip();
while(b.hasNext()){
System.out.println(b.get());
}
continue;
}else if(k.isWritable()){
SocketChanlle ch=(SocketChannel)k.channel();
String msj=Un mensaje;
ByteBuffer b=ByteBuffer.wrap(msj.getBytes());
ch.write(b);
continue;
//Enviar un entero,flotante,doble
ByteBuffer b=ByteBuffer.allocate(4);
b.putInt(x);

b.flip;
//Enviar un objeto
Objeto o=nre Objeto(.)
ByteArrayOutPutStream baos=new
ByteArrayOutputStream();
ObjectOutputStream oos=new
ObjectOutputStream(baos);
oss.writeObject(o);
oss.flush();
byte[]buf=baos.toByteArray();
ByteBuffer b=ByteBuffer.wrap(buf);
ch.write(b);

}
}
}
}catch(Exception e){
e.printStackTrace();
}
Clase SocketChannel(java.nio.channels.SocketChannel)
Opciones Configurables:

SO_SNDBUF
SO_RCVBUF
SO_KEEPALIVE
SO_REUSADOR
SO_LINGER
TCP_NODELAY

Constructor

Protected SocketChannel(SelectorProvider p)

Metodos

abstract SocketChannel bind(SocketAddress local)


abstract boolean connect(SocketAddress dst)
abstract boolean finishConect()

abstract boolean isConnected()


abstract boolean isConnectionPending()
static SocketChannel open()
abstract int read(ByteBuffer b)
abstract int write(ByteBuffer b)
abstract SocketChannel shutdownInput()
abstract SocketChannel shutdownOutput()

Creacion del Socket Cliente


try{
String host=127.0.0.1;
Int puerto=1234;
SocketChannel cl=SocketChannel.open();
cl.configutrBlocking(false);
InetSocketAddress dst=new InetSocketAddress(host,puerto);
cl.connect(dst);
Selector sel=Selector.open();
cl.register(sel,SelectionKey.OP_CONNECT);
while(true){
sel.select();
Iterator<SelectionKey>it=sel.selectedKeys().iterator();
While(it.hasNext()){
SelectionKey k=(SelectionKet)it.next();
It.remove();
If(k.isConnectable()){
SocketChannel ch=(SocketChannel)k.channel();
If(ch.isConnectionPending()){
Try{
Ch.finishConnect();
}catch(Exception e){
e.printStackTrace();
}

System.out.println(Conexin establecida);
ch.register(sel,SelectionKey.OP_READ|
SelectionKey.OP_WRITE);
continue;
}

//if(b.hasArray()){
ObjectInputStream ois=ObjectInputStream(new
ByteArrayInputStream(b.array()));
Objetot o=(Objeto1)ois.readObject();

Buffers
AllocateDirectr(Datos en ram continuos ->Mayor velocidad)
Allocate(Datos en ram discontinuos ->Menos velocidad)
Caracteristicas:
Position=0
Mark=nulo->Genera marcas con mtodo mark que sirven para
identificar posiciones
Limit=ultima posicion
Capacity=cantidad del buffer

b.limit(b.position());
b.position(0);
b.flip()->Posiciona limit a position, y position a 0
Metodos:
PutTipo();
GetTipo();
Metodo wrap utiliza
.allocate()
.put()
.flip()

148.204.58.221/axel/aplicaciones/sockets/ ->Servidor NB.java ClienteNB.java


/Sender.java Receiver.java

Das könnte Ihnen auch gefallen