Java File Read via ByteBuffer readStringFromSocketChannel(SocketChannel sc)

Here you can find the source of readStringFromSocketChannel(SocketChannel sc)

Description

read String From Socket Channel

License

Apache License

Declaration

public static String readStringFromSocketChannel(SocketChannel sc) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;

public class Main {
    private static Charset charset = Charset.forName("ISO-8859-2");
    private static final int BSIZE = 1024;

    public static String readStringFromSocketChannel(SocketChannel sc) {
        if (!sc.isOpen())
            return "";
        StringBuffer resultString = new StringBuffer();
        resultString.setLength(0);//from w  ww .j a  v a2  s  . c  o m
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        bbuf.clear();
        try {
            int loopCounter = 0;
            readLoop: while (true) {
                // System.out.println("while true in readloop");
                int n = sc.read(bbuf);
                if (n > 0) {
                    bbuf.flip();
                    CharBuffer cbuf = charset.decode(bbuf);
                    while (cbuf.hasRemaining()) {
                        // System.out.println("while true in hasremaining");
                        char c = cbuf.get();
                        if (c == '\r' || c == '\n')
                            break readLoop;
                        resultString.append(c);
                    }
                } else {
                    loopCounter++;
                    if (loopCounter > 1000) {
                        break readLoop;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (resultString.length() > 0) {
            // System.out.println("Message decoded from client: "+resultString.toString());
        }
        return resultString.toString();
    }
}

Related

  1. readShortBuffer(DataInputStream input)
  2. readShortByteArray(DataInput in)
  3. readString(ByteArrayInputStream bin)
  4. readString(ReadableByteChannel channel)
  5. readStringFromFile(String path)
  6. readStringInUTF8(DataInput in)
  7. readToBuffer(final String filename)
  8. readToByteArray(String fname)
  9. readTwoByteInt(byte[] array, int start)