首页 文章

通过ByteBuffer传输字符串

提问于
浏览
1

我需要通过bytebuffer传输2个整数和一个字符串 . 然后通过bytebuffer接收另一个字符串 .

必须有这样的东西:从keyboard.Enter读取x(int) . 从keyboard.Enter读取y(int) . 从键盘读取字符串 . 输入 . 所有值都在某处,正在处理,我必须收到字符串 . 一切都是通过socket通道完成的 .

我做过这样的事情:发送

Scanner scanner=new Scanner(System.in);
int m,n;
String str,result;
System.out.println("x=");
m=scanner.nextInt();
System.out.println("y=");
n=scanner.nextInt();
System.out.println("String: ");
str=scanner.next();

ByteBuffer bb=ByteBuffer.allocate(100);

bb.putInt(0,m).putInt(8,n).put(str.getBytes()); // problem?

try{

  sc.write(bb);
  bb.clear();
  sc.read(bb);

  CharBuffer cbuf = bb.asCharBuffer();
  result=cbuf.toString();

  System.out.println("Result : "+result);

接收:

ByteBuffer bb = ByteBuffer.allocate(100);    
  socketChannel.read(bb);
  int m=bb.getInt(0);
  int n=bb.getInt(8);
  String str=bb.toString().substring(16);

  App app=new App();
  String result=app.longestRepeatingSubstring(str,m,n);
  bb.clear();

  bb.put(result.getBytes());

  socketChannel.write(bb);
  socketChannel.close();

但我收到一个空字符串...

或者,如果我直接放入bb.toString()我收到这样的东西:java.nio.HeapByteBuffer [pos = 237 lim = 258 cap = 798]

1 回答

  • 0
    bb.putInt(0,m).putInt(8,n).put(str.getBytes()); // problem?
    

    是的问题 put(str.getBytes()) 依赖于先前设置的缓冲区中的位置,但因为您使用的是偏移的putInt函数,所以它不会 .

    bb.putInt(0,m).putInt(8,n).position(16).put(str.getBytes()).position(0);
    

    此行不适用于您的客户端 ByteBuffer.toString() 返回缓冲区状态而不是内容,

    代替

    String str=bb.toString().substring(16);
    

    你要

    byte[] b = new byte[length];
    bb.position(16);
    bb.get(b);
    String str=new String(b);
    

相关问题