0

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

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

I would like to add that if you yourself are flipping the buffer in your code this extra flip() added by this is very necessary as get() changes where the next read from the buffer happens and can lead to unexpected behaviour. (in my case, OpenGL driver crashes)
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.