I built a server and client using NIO package with server socket channel and socket channel. The basic setup works. but when I try to move my code handling each connection in a separate thread using executor service I start getting weird errors where I am getting partial message or sometimes blank messages.
This is my code where am I passing my selection key to a thread with executor service
private void readAndRespond(SelectionKey selectionKey) {
this.executorService.submit(new Worker(selectionKey));
}
private class Worker implements Runnable {
private SelectionKey selectionKey;
private Worker(SelectionKey selectionKey) {
this.selectionKey = selectionKey;
}
@Override
public void run() {
SocketChannel socketChannel;
ArrayList<ByteBuffer> buffers;
String data, reply;
ByteBuffer responseBuffer;
socketChannel = (SocketChannel) selectionKey.channel();
try {
buffers = this.readRequest(socketChannel);
data = this.extractData(buffers);
if (!data.isEmpty()) {
reply = responseManager.reply(data);
responseBuffer = ByteBuffer.wrap(reply.getBytes());
socketChannel.write(responseBuffer);
}
}
catch (IOException e) {
System.out.println("Unable to process response " + e.getMessage());
}
}
private ArrayList<ByteBuffer> readRequest(SocketChannel socketChannel) throws IOException {
int counter;
ByteBuffer current;
ArrayList<ByteBuffer> buffers;
counter = 2;
buffers = new ArrayList<>();
current = ByteBuffer.allocate(minBuffer);
buffers.add(current);
while (socketChannel.read(current) > 0) {
if (!current.hasRemaining()) {
current = ByteBuffer.allocate(minBuffer * 2 * counter);
buffers.add(current);
counter++;
}
}
return buffers;
}
private String extractData(ArrayList<ByteBuffer> buffers) throws UnsupportedEncodingException {
StringBuilder stringBuilder;
stringBuilder = new StringBuilder();
for(ByteBuffer buffer : buffers) {
stringBuilder.append(new String(buffer.array(), "UTF-8"));
}
return stringBuilder.toString().trim();
}
}
在移交给线程阅读之前需要添加它
selectionKey.interestOps( selectionKey.interestOps() & ~SelectionKey.OP_READ );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.