I have started my work on a pre-developed Java application, where they are dealing with java sockets. The main concept of the project is to get data from the client at the java socket server and process it.
The project has been developed using Java NIO ServerSocketChannel.
Now in this scenario, I could able to get around 70-80 records per second from the client. While if I use simple Java ServerSocket ( Just for testing purpose ) the output zoomed to around 800 reps.
Why is so much difference in both of this? And how can I modify ServerSocketChannel to imitate ServerSocket?
Here is my main processing part,
SocketChannel client = (SocketChannel) key.channel();
if (!key.isReadable()) {
key.cancel();
client.close();
continue;
}
int[] k = (int[]) key.attachment();
if (k[2] == 0) {
ByteBuffer lengthBuffer = ByteBuffer.allocate(2);
int bytesRead = -1;
if (!client.socket().isClosed() && key.isValid()) {
bytesRead = client.read(lengthBuffer);
}
if (bytesRead == -1) {
key.cancel();
client.close();
continue;
}
lengthBuffer.flip();
byte[] bytes = new byte[2];
lengthBuffer.get(bytes, 0, 2);
short length = DRMSDecoder.getShort(bytes);
k[0]++;
k[1] = length;
k[2] = 1;
key.attach(k);
lengthBuffer.clear();
}
else {
try {
int length = k[1];
ByteBuffer dataBuffer = ByteBuffer.allocate(length);
dataBuffer.clear();
System.gc();
int bytesRead = -1;
if (!client.socket().isClosed() && key.isValid()) {
bytesRead = client.read(dataBuffer);
}
if (bytesRead == -1) {
key.cancel();
client.close();
continue;
}
dataBuffer.flip();
Hashtable<String, Object> request = decoder.decode(dataBuffer);
short call_type = (Short) request.get("Call Type");
if (request.get("Call Type") != null && (((Short) request.get("Call Type")) == 78 || ((Short) request.get("Call Type")) == 80)) {
} else if (request.get("Call Type") != null && (((Short) request.get("Call Type")) == 79)) {
key.cancel();
client.close();
}
String message = (String) request.get("Buffer");
handleMessage(message);
}
k[0]++;
k[2] = 0;
key.attach(k);
lastMessageProcessed++;
dataBuffer.clear();
} catch (Exception e) {
// System.out.println(e);
}
}