buill bogger
buill bogger

Reputation: 9

how to print string from bytebuffer

i have just started playing around with java nio packages an am at a bit of a loss i have a client

Socket s=new Socket(ip,port);
OutputStream out=new OutputStream();
PrintStream ps=new PrintStream(s.getOutputStream());
String t=""hiya";
ps.print(t);
ps.flush();
InputSTreamReader in=new InputSTreamReader(s.getInputSTream);
BufferReader b=nwe BufferedReader(in);
System.out.println(b.readLine());//prints echo response from server

and on the server side

this.selkey = selkey;
this.chan = (SocketChannel) chan.configureBlocking(false); // asynchronous/non-blocking
buf = ByteBuffer.allocateDirect(64); // 64 byte capacity

void read() {   
    try {
        int amount_read = -1;
        try { 
           amount_read = chan.read((ByteBuffer) buf.clear());                    
        } catch (Throwable t) { 
            }
        if (amount_read == -1)
            disconnect();//deelts client on exit
        if (amount_read < 1)
            return; // if zero
            System.out.println("sending back " + buf.position() + " bytes");
            // turn this bus right around and send it back!
            buf.flip();
            chan.write(buf);//sending data 2 client
    } catch (Throwable t) {
            disconnect();
            t.printStackTrace();
    }
}

what this does i send string t to the server into bytebuffer and echos it back which all works fine but hoiw would i print the string on the server side for example in read method

buf.flip()
System.out.write(buff);//which just prints what looks to be chinese

Upvotes: 0

Views: 3938

Answers (2)

Keshav
Keshav

Reputation: 1133

Since you are sending data as bytes, it wont work as Strings. Even if you did, it would be referencing the byte array. Try this:

String str = new String (buff);

Upvotes: 0

buill bogger
buill bogger

Reputation: 9

k this is typical have been working on this problem for like an hour but when i post the question the answer acours to me CAST IT TO A CHAR!

this works

buf.flip();
while (buf.hasRemaining()) {
    System.out.print((char) buf.get();
}
System.out.println();

Upvotes: 1

Related Questions