2015-10-22 20:02:55 +02:00
|
|
|
package com.jenkov.nioserver;
|
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
import java.nio.ByteBuffer;
|
|
|
|
import java.nio.channels.SocketChannel;
|
|
|
|
|
|
|
|
/**
|
2019-12-28 10:43:48 +01:00
|
|
|
* Project: <strong>java-nio-server</strong><br>
|
|
|
|
* File: <strong>Socket.java</strong><br>
|
|
|
|
* Created: <strong>16 Oct 2015</strong><br>
|
|
|
|
*
|
|
|
|
* @author jjenkov
|
2015-10-22 20:02:55 +02:00
|
|
|
*/
|
|
|
|
public class Socket {
|
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
public long socketId;
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
public SocketChannel socketChannel;
|
|
|
|
public IMessageReader messageReader;
|
|
|
|
public MessageWriter messageWriter;
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
public boolean endOfStreamReached;
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
public Socket(SocketChannel socketChannel) { this.socketChannel = socketChannel; }
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
public int read(ByteBuffer byteBuffer) throws IOException {
|
|
|
|
int bytesRead = socketChannel.read(byteBuffer);
|
|
|
|
int totalBytesRead = bytesRead;
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
while (bytesRead > 0) {
|
|
|
|
bytesRead = socketChannel.read(byteBuffer);
|
|
|
|
totalBytesRead += bytesRead;
|
|
|
|
}
|
|
|
|
if (bytesRead == -1) endOfStreamReached = true;
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
return totalBytesRead;
|
|
|
|
}
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
public int write(ByteBuffer byteBuffer) throws IOException {
|
|
|
|
int bytesWritten = socketChannel.write(byteBuffer);
|
|
|
|
int totalBytesWritten = bytesWritten;
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
while (bytesWritten > 0 && byteBuffer.hasRemaining()) {
|
|
|
|
bytesWritten = socketChannel.write(byteBuffer);
|
|
|
|
totalBytesWritten += bytesWritten;
|
|
|
|
}
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
return totalBytesWritten;
|
|
|
|
}
|
2015-10-22 20:02:55 +02:00
|
|
|
|
|
|
|
}
|