【发布时间】:2015-03-07 18:08:08
【问题描述】:
喂,
我有以下代码:
public AppThread(SocketChannel socketChannel){
this.socketChannel=socketChannel;
}
public void run(){
try{
ByteBuffer bb = ByteBuffer.allocate(11);
socketChannel.read(bb);
//byte[] b = new byte[bb.capacity()];
// bb.get(b, 0, 11);
System.out.println(bb.toString());
byte[] a = new byte[11];
CharBuffer cb = bb.asCharBuffer();
System.out.println(cb);
bb.get(a);
App app=new App();
// String an = new String(b);
//String zodie = Zodie.getZodie(an);
//b = new byte[zodie.length()];
//b = zodie.getBytes();
bb.clear();
//bb.put(b);
socketChannel.write(bb);
socketChannel.close();
}
catch(IOException e){
System.err.println("Server comunication error : "+e.getMessage());
}
}
}
还有接收字符串并返回字符串的zodie静态方法。
如何将字符串写入 SocketChannel 以将其作为参数传递给 zodiac 静态方法。
我提到在客户端我发送了一个字节数组,我已经检查过了,没关系。
客户端:
byte[] a = an.getBytes();
System.out.println(new String(a));
ByteBuffer bb=ByteBuffer.allocate(11);
// Varianta 1
bb.put(a);
// Varianta 2
// LongBuffer lb=bb.asLongBuffer();
// lb.put(0,m).put(1,n);
try{
sc.write(bb);
bb.clear();
sc.read(bb);
// Varianta 1
//a = new byte[bb.remaining()];
zodie=bb.toString();
// Varianta 2
// r=lb.get(0);
System.out.println("Zodia : "+ zodie);
sc.close();
此致,
我收到服务器错误:
Server ready...
java.nio.HeapByteBuffer[pos=1 lim=11 cap=11]
Exception in thread "pool-1-thread-1" java.nio.BufferUnderflowException
at java.nio.HeapByteBuffer.get(Unknown Source)
at java.nio.ByteBuffer.get(Unknown Source)
at server.AppThread.run(AppThread.java:27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
【问题讨论】: