/*
* Created by Andrey Cherkashin (acherkashin)
* http://acherkashin.me
*
* License
* Copyright (c) 2015 Andrey Cherkashin
* The project released under the MIT license: http://opensource.org/licenses/MIT
*/
package ragefist.core.network;
import java.io.IOException;
import java.net.ConnectException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author acherkashin
*/
public class SocketStrategyConsole implements ISocketStrategy
{
private static final Charset _charset = Charset.defaultCharset();
private final static ISocketStrategy _instance = new SocketStrategyConsole();
public static final ISocketStrategy getInstance() { return _instance; }
@Override
public byte[][] readPackets(SocketClient socket, ByteBuffer readBuffer) throws IOException {
List<byte[]> packets = new ArrayList<>();
int bytesRead;
while((bytesRead = socket.read(readBuffer)) > 0) {
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes, 0, bytes.length);
int lastOffset = 0;
for(int i = 0; i < bytes.length; i++) {
if (bytes[i] == 13 && i + 1 < bytes.length && bytes[i + 1] == 10) { // \r\n
packets.add(Arrays.copyOfRange(bytes, lastOffset, i));
lastOffset = i + 2;
}
}
readBuffer.clear();
}
if (bytesRead < 0) {
throw new ConnectException();
}
byte[][] array = new byte[packets.size()][];
for(int i = 0; i < array.length; i++) {
byte[] byteArray = packets.get(i);
array[i] = byteArray;
}
return array;
}
@Override
public int writePacket(SocketClient socket, String packet) throws IOException {
return socket.write(_charset.encode(packet));
}
@Override
public int writePacket(SocketClient socket, byte[] bytes) throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
return socket.write(buffer);
}
}