我刚刚开始玩 java nio 包,有点不知所措 我有一个客户
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
在服务器端
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();
}
}
这是做什么的,我将字符串 t 发送到服务器到字节缓冲区并回显它,一切正常,但是我如何在服务器端打印字符串,例如在读取方法中
buf.flip()
System.out.write(buff);//which just prints what looks to be chinese
最佳答案
这是典型的,我已经在这个问题上工作了大约一个小时,但是当我发布问题时,答案出现在我面前 将其转化为炭!
这有效
buf.flip();
while (buf.hasRemaining()) {
System.out.print((char) buf.get();
}
System.out.println();
关于java - 如何从字节缓冲区打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27473727/