This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
java-nio-server/src/main/java/com/jenkov/nioserver/Socket.java

58 lines
1.4 KiB
Java

package com.jenkov.nioserver;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
/**
* Created by jjenkov on 16-10-2015.
*/
public class Socket {
public long socketId;
public SocketChannel socketChannel = null;
public IMessageReader messageReader = null;
public IMessageWriter messageWriter = null;
public boolean endOfStreamReached = false;
public Socket() {
}
public Socket(SocketChannel socketChannel) {
this.socketChannel = socketChannel;
}
public int read(ByteBuffer byteBuffer) throws IOException {
int bytesRead = this.socketChannel.read(byteBuffer);
int totalBytesRead = bytesRead;
while(bytesRead > 0){
bytesRead = this.socketChannel.read(byteBuffer);
totalBytesRead += bytesRead;
}
if(bytesRead == -1){
this.endOfStreamReached = true;
}
return totalBytesRead;
}
public int write(ByteBuffer byteBuffer) throws IOException{
int bytesWritten = this.socketChannel.write(byteBuffer);
int totalBytesWritten = bytesWritten;
while(bytesWritten > 0 && byteBuffer.hasRemaining()){
bytesWritten = this.socketChannel.write(byteBuffer);
totalBytesWritten += bytesWritten;
}
return totalBytesWritten;
}
}