소켓 채널
소켓 채널 (SocketChannel)
스트림 지향 연결 소켓을 위한 선택 가능 채널이에요. 연결·읽기·쓰기와 비차단 연결을 지원합니다.
본문
SocketChannel은 스트림 지향 연결 소켓을 위한 선택 가능 채널이에요. 소켓 채널은 open() 메서드로 만듭니다.
public abstract class SocketChannel extends AbstractSelectableChannel
implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel
public static SocketChannel open() throws IOException
public static SocketChannel open(ProtocolFamily family) throws IOException
public static SocketChannel open(SocketAddress remote) throws IOException
새로 만든 소켓 채널은 열려 있지만 아직 연결되지 않았어요. 연결되지 않은 채널에 I/O 연산을 시도하면 NotYetConnectedException이 던져집니다. connect() 메서드로 연결하고, isConnected()로 연결 여부를 확인할 수 있어요.
소켓 채널은 비차단 연결을 지원합니다.
public abstract boolean connect(SocketAddress remote) throws IOException
public abstract boolean finishConnect() throws IOException
public abstract boolean isConnected()
public abstract boolean isConnectionPending()
connect()— 연결을 시작하고, 비차단 모드에서는 즉시 반환해요.finishConnect()— 진행 중인 연결을 완료해요.isConnectionPending()— 연결 작업이 진행 중인지 확인합니다.
데이터 전송:
public abstract int read(ByteBuffer dst) throws IOException
public abstract long read(ByteBuffer[] dsts, int offset, int length) throws IOException
public abstract int write(ByteBuffer src) throws IOException
public abstract long write(ByteBuffer[] srcs, int offset, int length) throws IOException
public abstract SocketChannel shutdownInput() throws IOException
public abstract SocketChannel shutdownOutput() throws IOException
소켓 채널은 비동기 종료(asynchronous shutdown)를 지원하고, shutdownInput()/shutdownOutput()으로 입력·출력 방향을 각각 종료할 수 있어요. 여러 동시 스레드가 사용하기에 안전합니다.