Java Code Examples for java.nio.channels.SocketChannel#read()

The following examples show how to use java.nio.channels.SocketChannel#read() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DeviceMonitor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fills a buffer by reading data from a socket.
 * @return the content of the buffer as a string, or null if it failed to convert the buffer.
 * @throws IOException if there was not enough data to fill the buffer
 */
@Nullable
private static String read(@NonNull SocketChannel socket, @NonNull byte[] buffer)
        throws IOException {
    ByteBuffer buf = ByteBuffer.wrap(buffer, 0, buffer.length);

    while (buf.position() != buf.limit()) {
        int count;

        count = socket.read(buf);
        if (count < 0) {
            throw new IOException("EOF");
        }
    }

    try {
        return new String(buffer, 0, buf.position(), AdbHelper.DEFAULT_ENCODING);
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
 
Example 2
Source File: ChannelOperationsHandlerTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
	try {
		server.configureBlocking(true);
		server.socket()
		      .bind(new InetSocketAddress(port));
		countDown();
		thread = Thread.currentThread();
		SocketChannel ch = server.accept();
		while (true) {
			int bytes = ch.read(ByteBuffer.allocate(256));
			if (bytes > 0) {
				ch.close();
				server.socket().close();
				return;
			}
		}
	}
	catch (IOException e) {
		log.error("", e);
	}
}
 
Example 3
Source File: NioServer.java    From marauroa with GNU General Public License v2.0 5 votes vote down vote up
private void read(SelectionKey key) {
	SocketChannel socketChannel = (SocketChannel) key.channel();

	// Clear out our read buffer so it's ready for new data
	this.readBuffer.clear();

	// Attempt to read off the channel
	int numRead;
	try {
		numRead = socketChannel.read(this.readBuffer);
	} catch (IOException e) {
		// The remote forcibly closed the connection, cancel
		// the selection key and close the channel.
		logger.debug("Remote closed connnection", e);
		key.cancel();

		close(socketChannel);

		return;
	}

	if (numRead == -1) {
		// Remote entity shut the socket down cleanly. Do the
		// same from our end and cancel the channel.
		logger.debug("Remote closed connnection cleanly");
		close((SocketChannel) key.channel());

		key.cancel();
		return;
	}

	// Hand the data off to our worker thread
	this.worker.onData(this, socketChannel, this.readBuffer.array(), numRead);
}
 
Example 4
Source File: Io.java    From PlusDemo with Apache License 2.0 5 votes vote down vote up
private static void nio2() {
    try {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        SocketChannel socketChannel = serverSocketChannel.accept();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (socketChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: MultiThreadNIOEchoClient.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
/**
 * @author 梦境迷离
 * @throws IOException
 * @description 读取
 * @time 2018年3月28日
 */
private void read(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    // 创建读取缓冲区
    ByteBuffer byteBuffer = ByteBuffer.allocate(100);
    channel.read(byteBuffer);
    byte[] data = byteBuffer.array();
    String msg = new String(data).trim();
    System.out.println("客户端收到消息:" + msg);
    channel.close();
    key.selector().close();
}
 
Example 6
Source File: TestBlockingNIO.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@Test
public void server() throws IOException {
    // 1. 获取通道
    ServerSocketChannel ssChannel = ServerSocketChannel.open();

    FileChannel outChannel =
            FileChannel.open(
                    Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

    // 2. 绑定连接
    ssChannel.bind(new InetSocketAddress(9898));

    // 3. 获取客户端连接的通道
    SocketChannel sChannel = ssChannel.accept();

    // 4. 分配指定大小的缓冲区
    ByteBuffer buf = ByteBuffer.allocate(1024);

    // 5. 接收客户端的数据,并保存到本地
    while (sChannel.read(buf) != -1) {
        buf.flip();
        outChannel.write(buf);
        buf.clear();
    }

    // 6. 关闭通道
    sChannel.close();
    outChannel.close();
    ssChannel.close();
}
 
Example 7
Source File: RequestReader.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private Command readAsciiCommand() throws IOException {
  SocketChannel channel = this.socket.getChannel();
  if (channel == null || !channel.isOpen()) {
    throw new IllegalStateException("cannot read from channel");
  }
  buffer.clear();
  channel.read(buffer);
  buffer.flip();
  oneRequest = buffer.duplicate();
  return Command.valueOf(readCommand(oneRequest));
}
 
Example 8
Source File: RCONServer.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
private void read(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    int bytesRead;
    try {
        bytesRead = channel.read(buffer);
    } catch (IOException exception) {
        key.cancel();
        channel.close();
        if (this.rconSessions.contains(channel)) {
            this.rconSessions.remove(channel);
        }
        if (this.sendQueues.containsKey(channel)) {
            this.sendQueues.remove(channel);
        }
        return;
    }

    if (bytesRead == -1) {
        key.cancel();
        channel.close();
        if (this.rconSessions.contains(channel)) {
            this.rconSessions.remove(channel);
        }
        if (this.sendQueues.containsKey(channel)) {
            this.sendQueues.remove(channel);
        }
        return;
    }

    buffer.flip();
    this.handle(channel, new RCONPacket(buffer));
}
 
Example 9
Source File: NioSslIntegrationTest.java    From Chronicle-Network with Apache License 2.0 5 votes vote down vote up
private void testDataConnection(final SocketChannel channel, final SocketChannel serverConnection) throws IOException {
    final ByteBuffer message = ByteBuffer.wrap("test message".getBytes(StandardCharsets.US_ASCII));

    while (message.hasRemaining()) {
        channel.write(message);
    }

    message.clear();
    while (message.hasRemaining()) {
        serverConnection.read(message);
    }

    message.flip();
    assertThat(new String(message.array()), is("test message"));
}
 
Example 10
Source File: Test01.java    From jdk-source-analysis with Apache License 2.0 5 votes vote down vote up
private void readClientDate(SelectionKey selectionKey) throws IOException {
    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
    int read = socketChannel.read(byteBuffer);
    if (read > 0) {
        String s = new String(byteBuffer.array());
        writeClientData(socketChannel, s);
        System.out.printf("%8d, %s", byteBuffer.position(), s);
    }
}
 
Example 11
Source File: NIOClient.java    From spring-boot-demo with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        InetSocketAddress socketAddress = new InetSocketAddress("0.0.0.0", 10002);
        SocketChannel socketChannel = SocketChannel.open(socketAddress);

        log.info("连接 BIOServer 服务,端口:10002...");

        ArrayList<String> companyDetails = new ArrayList<>();

        // 创建消息列表
        companyDetails.add("腾讯");
        companyDetails.add("阿里巴巴");
        companyDetails.add("京东");
        companyDetails.add("百度");
        companyDetails.add("google");

        for (String companyName : companyDetails) {
            socketChannel.write(ByteBuffer.wrap(companyName.getBytes()));
            log.info("发送: " + companyName);

            ByteBuffer buffer = ByteBuffer.allocate(BUFF_SIZE);
            buffer.clear();
            socketChannel.read(buffer);
            String result = new String(buffer.array()).trim();
            log.info("收到NIOServer回复的消息:" + result);

            // 等待2秒钟再发送下一条消息
            Thread.sleep(2000);
        }

        socketChannel.close();
    }
 
Example 12
Source File: AsyncPacketReader.java    From mpush-client-java with Apache License 2.0 5 votes vote down vote up
private boolean read(SocketChannel channel, ByteBuffer in) {
    int readCount;
    try {
        readCount = channel.read(in);
        connection.setLastReadTime();
    } catch (IOException e) {
        logger.e(e, "read packet ex, do reconnect");
        readCount = -1;
        sleep4Reconnect();
    }
    return readCount > 0;
}
 
Example 13
Source File: SocketProxyTest.java    From rxmqtt with Apache License 2.0 4 votes vote down vote up
protected void readFromClient(final Selector selector, final SelectionKey key, 
        final ByteBuffer buffer)
          throws IOException {
    
    logger.info("Proxy reading from client.");
    
    // Get the client channel from key
    final SocketChannel client = (SocketChannel) key.channel();
    logger.info("Client channel blocking: " + client.isBlocking());
    
    // Get the remote channel
    SocketChannel remote = proxy.get(key.channel());
    if (remote != null ) {
        logger.info("Remote channel blocking: " + remote.isBlocking());
    } else {
        logger.info("Remote channel is null.");
    }
    
    // Allocate buffer for data from client
    ByteBuffer fromClient = ByteBuffer.allocateDirect(BYTE_BUFFER_SIZE);
    
    // Read from the client to the buffer
    int read = client.read(fromClient);                    

    // We have stopped reading
    if (read < 0) { 
        
        logger.info("Client sent no data, closing channels.");
        
        // Remove proxy and close socket channel
        if (remote != null ) {
            remote.close();
            proxy.remove(client);
        }
    }
    
    // We are reading
    if (read > 0) { 
        // Client sent data
        fromClient.flip();
        logger.info("Client sent data: " + StandardCharsets.UTF_8.decode(fromClient.duplicate()));
        // Check if the proxy is enabled
        if (this.enabed.get()) {
            // Send to remote if enabled
            logger.info("Enabled, sending data to remote");
            while(fromClient.hasRemaining()) {
                remote.write(fromClient);
            }
            //remote.write(fromClient);
        } else {
            logger.info("Disabled, not sending data to remote");
        }
        fromClient.clear();
        client.register(selector, SelectionKey.OP_READ);                                        
    }
}
 
Example 14
Source File: JamesServerWithRetryConnectionTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
private String getServerConnectionResponse(SocketChannel socketChannel) throws IOException {
    ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
    socketChannel.read(byteBuffer);
    byte[] bytes = byteBuffer.array();
    return new String(bytes, Charset.forName("UTF-8"));
}
 
Example 15
Source File: AdbHelper.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Runs a log service on the {@link Device}, and provides its output to the {@link LogReceiver}.
 * <p/>This call is blocking until {@link LogReceiver#isCancelled()} returns true.
 * @param adbSockAddr the socket address to connect to adb
 * @param device the Device on which to run the service
 * @param logName the name of the log file to output
 * @param rcvr the {@link LogReceiver} to receive the log output
 * @throws TimeoutException in case of timeout on the connection.
 * @throws AdbCommandRejectedException if adb rejects the command
 * @throws IOException in case of I/O error on the connection.
 */
public static void runLogService(InetSocketAddress adbSockAddr, Device device, String logName,
        LogReceiver rcvr) throws TimeoutException, AdbCommandRejectedException, IOException {
    SocketChannel adbChan = null;

    try {
        adbChan = SocketChannel.open(adbSockAddr);
        adbChan.configureBlocking(false);

        // if the device is not -1, then we first tell adb we're looking to talk
        // to a specific device
        setDevice(adbChan, device);

        byte[] request = formAdbRequest("log:" + logName);
        write(adbChan, request);

        AdbResponse resp = readAdbResponse(adbChan, false /* readDiagString */);
        if (!resp.okay) {
            throw new AdbCommandRejectedException(resp.message);
        }

        byte[] data = new byte[16384];
        ByteBuffer buf = ByteBuffer.wrap(data);
        while (true) {
            int count;

            if (rcvr != null && rcvr.isCancelled()) {
                break;
            }

            count = adbChan.read(buf);
            if (count < 0) {
                break;
            } else if (count == 0) {
                try {
                    Thread.sleep(WAIT_TIME * 5);
                } catch (InterruptedException ie) {
                }
            } else {
                if (rcvr != null) {
                    rcvr.parseNewData(buf.array(), buf.arrayOffset(), buf.position());
                }
                buf.rewind();
            }
        }
    } finally {
        if (adbChan != null) {
            adbChan.close();
        }
    }
}
 
Example 16
Source File: TCPInput.java    From Virtual-Hosts with GNU General Public License v3.0 4 votes vote down vote up
private void processInput(SelectionKey key, Iterator<SelectionKey> keyIterator)
{
    keyIterator.remove();
    ByteBuffer receiveBuffer = ByteBufferPool.acquire();
    // Leave space for the header

    TCB tcb = (TCB) key.attachment();
    synchronized (tcb)
    {
        Packet referencePacket = tcb.referencePacket;
        receiveBuffer.position(referencePacket.IP_TRAN_SIZE);
        SocketChannel inputChannel = (SocketChannel) key.channel();
        int readBytes;
        try
        {
            readBytes = inputChannel.read(receiveBuffer);
        }
        catch (IOException e)
        {
            LogUtils.e(TAG, "Network read error: " + tcb.ipAndPort, e);
            referencePacket.updateTCPBuffer(receiveBuffer, (byte) Packet.TCPHeader.RST, 0, tcb.myAcknowledgementNum, 0);
            outputQueue.offer(receiveBuffer);
            TCB.closeTCB(tcb);
            return;
        }

        if (readBytes == -1)
        {
            // End of stream, stop waiting until we push more data
            key.interestOps(0);
            tcb.waitingForNetworkData = false;

            if (tcb.status != TCB.TCBStatus.CLOSE_WAIT)
            {
                ByteBufferPool.release(receiveBuffer);
                return;
            }

            tcb.status = TCB.TCBStatus.LAST_ACK;
            referencePacket.updateTCPBuffer(receiveBuffer, (byte) Packet.TCPHeader.FIN, tcb.mySequenceNum, tcb.myAcknowledgementNum, 0);
            tcb.mySequenceNum++; // FIN counts as a byte
        }
        else
        {
            // XXX: We should ideally be splitting segments by MTU/MSS, but this seems to work without
            referencePacket.updateTCPBuffer(receiveBuffer, (byte) (Packet.TCPHeader.PSH | Packet.TCPHeader.ACK),
                    tcb.mySequenceNum, tcb.myAcknowledgementNum, readBytes);
            tcb.mySequenceNum += readBytes; // Next sequence number
            receiveBuffer.position(referencePacket.IP_TRAN_SIZE + readBytes);
        }
    }
    outputQueue.offer(receiveBuffer);
}
 
Example 17
Source File: CassandraNodeConfTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
private String getServerConnectionResponse(SocketChannel socketChannel) throws IOException {
    ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
    socketChannel.read(byteBuffer);
    byte[] bytes = byteBuffer.array();
    return new String(bytes, Charset.forName("UTF-8"));
}
 
Example 18
Source File: ChannelReader.java    From Mycat-Balance with Apache License 2.0 4 votes vote down vote up
public static ByteBuf read(SocketChannel socketChannel, ChannelContext channelContext) throws IOException
{
	byteBuffer.clear(); // 复位buffer,准备接收数据

	if (log.isDebugEnabled())
	{
		log.debug("{},buffer before read:{}", channelContext, byteBuffer);
	}

	int countOfRead = socketChannel.read(byteBuffer);

	long receivedBytes = channelContext.getStatVo().getReceivedBytes() + countOfRead;
	channelContext.getStatVo().setReceivedBytes(receivedBytes);
	if (log.isDebugEnabled())
	{
		log.debug("{} has received {} bytes", channelContext.getId(), receivedBytes);

		log.debug("{},buffer after read:{}", channelContext, byteBuffer);
	}

	if (countOfRead == -1)
	{
		String string = "count of read is -1, " + channelContext.getId();
		log.error(string);
		throw new EOFException(string);
		//            NioUtils.remove(channelContext, string);
		//            channelContext.getReadIOErrorHandler().handle(socketChannel, (IOException) null, channelContext, "count of read is -1");
		//            return null;
	}
	if (countOfRead == 0)
	{
		log.warn("0 byte read {}", channelContext.getId());
		return null;
	}

	channelContext.getStatVo().setCurrentReceivedTime(SystemTimer.currentTimeMillis());

	receivedByteCount.addAndGet(countOfRead);
	if (log.isDebugEnabled())
	{
		log.debug(("received {} bytes, all received {} bytes"), countOfRead, receivedByteCount.get());
	}

	// byte[] datas = new byte[byteBuffer.position()];
	byteBuffer.flip(); // 准备读数据
	// byteBuffer.get(datas); // 将数据从buffer读到字节数组中

	ByteBuf buf1 = Unpooled.copiedBuffer(byteBuffer);

	readCount.incrementAndGet();
	channelContext.getStatVo().getReadCount().incrementAndGet();

	return buf1;

}
 
Example 19
Source File: NIOConnector.java    From ServletContainer with GNU General Public License v3.0 4 votes vote down vote up
public void read(SelectionKey selectionKey) throws IOException {
    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
    ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
    socketChannel.read(byteBuffer);
    String request = new String(byteBuffer.array()).trim();
}
 
Example 20
Source File: AESocksProxyConnectionImpl.java    From BiglyBT with GNU General Public License v2.0 3 votes vote down vote up
@Override
protected boolean
readSupport(
	SocketChannel 		sc )

	throws IOException
{
	int	len = sc.read( buffer );

	if ( len == 0 ){

		return( false );

	}else if ( len == -1 ){

		throw( new IOException( "Connection closed" ));
	}


	if ( buffer.hasRemaining()){

		return( true );
	}

	buffer.flip();

	byte[]	bytes = new byte[16];

	buffer.get( bytes );

	InetAddress inet_address = InetAddress.getByAddress( bytes );

	new proxyStateV5RequestPort( "", inet_address );

	return( true );
}