Olá possuo as seguintes classes para criar e ler a partir de um socket, mas está ocorrendo o seguinte erro:
java.nio.channels.ClosedChannelException
at sun.nio.ch.SocketChannelImpl.ensureReadOpen(SocketChannelImpl.java:236)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:279)
at com.Communicator$Listener.bytesRead(Communicator.java:152)
at com.Communicator$Listener.run(Communicator.java:121)
public Communicator(String defaultIP) {
int aux = DEFAULT_PORT;
this.defaultIP = defaultIP;
boolean created = false;
clientSocketList = new LinkedHashMap<String, SocketChannel>();
while (!created) {
try {
serverChannel = ServerSocketChannel.open();
channelAddress = new InetSocketAddress(this.defaultIP, aux);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
try {
serverChannel.socket().bind(channelAddress);
created = true;
} catch (IOException e) {
aux++;
}
}
this.active = true;
this.start();
}
public Communicator() {
}
@Override
public void connectServer(String hostDescription) {
try {
String vet[] = hostDescription.split(":");
String hostname = vet[0];
int port = Integer.parseInt(vet[1].trim());
clientChannel = SocketChannel.open(new InetSocketAddress(hostname, port));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
rodaListener();
}
public void run() {
try {
while (this.active) {
try {
clientChannel = serverChannel.accept();
clientSocketList.put(clientRemoteChannelDesc(), clientChannel);
rodaListener();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class Listener extends Thread {
private boolean listening;
SocketChannel clientChannel;
int nBytes;
public Listener(SocketChannel clientChannel) {
try {
this.clientChannel = clientChannel;
this.listening = true;
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
while (listening) {
ByteBuffer header = bytesRead(6);
if (header == null) {
clientChannel.close();
} else {
header.getShort(); // Msg_Type
int size = header.getInt();
header.rewind();
ByteBuffer body = bytesRead(size - 6);
ByteBuffer msg = ByteBuffer.allocate(size);
msg.put(header).put(body).flip();
try {
incoming.put(msg);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public ByteBuffer bytesRead(int bytes) throws IOException {
try {
ByteBuffer msg = ByteBuffer.allocate(bytes);
int readBytes = 0;
while (readBytes < bytes) {
int readCount = clientChannel.read(msg);
if (readCount == -1) {
clientChannel.close();
}
readBytes += readCount;
}
msg.flip();
return msg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private void rodaListener() {
try {
Listener l = new Listener(clientChannel);
l.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Alguem poderia me auxliar? Ou há algum erro de implementação?