這是我已經試過:發送串無法正常工作
服務器:
import java.net.InetSocketAddress;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class JavaApplication12 {
public static void main(String[] args) throws Exception{
Charset charset = Charset.forName("ISO-8859-1");
ServerSocketChannel s = ServerSocketChannel.open();
s.configureBlocking(true);
s.socket().bind(new InetSocketAddress(1024));
CharBuffer c = CharBuffer.wrap("Hello from server!");
System.out.println("writing " + c);
ByteBuffer b = charset.encode(c);
SocketChannel sc = s.accept();
sc.configureBlocking(true);
b.flip();
int a = sc.write(b);
sc.close();
s.close();
System.out.println("wrote " + a);
}
}
客戶:
import java.net.InetSocketAddress;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class JavaApplication11 {
public static void main(String[] args) throws Exception {
Charset charset = Charset.forName("ISO-8859-1");
SocketChannel sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1024));
sc.configureBlocking(true);
ByteBuffer b = ByteBuffer.allocate(32);
b.flip();
int a = sc.read(b);
sc.close();
b.flip();
CharBuffer c = charset.decode(b);
c.flip();
System.out.println("Got " + c);
System.out.println("read " + a);
}
}
對方似乎只得到一個很長而空的字符串,我無法弄清楚我做錯了什麼。
更新:我更新了我的代碼,發現服務器正在寫0字節。有字節要寫,那爲什麼不寫sc.write()
?
更新2:隨着維沙爾的幫助下,我們終於有了一個可行的解決方案:
服務器:
Charset charset = Charset.forName("ISO-8859-1");
ServerSocketChannel s = ServerSocketChannel.open();
s.configureBlocking(true);
s.socket().bind(new InetSocketAddress(1024));
CharBuffer c = CharBuffer.wrap("Hello from server!");
ByteBuffer b = charset.encode(c);
SocketChannel sc = s.accept();
sc.configureBlocking(true);
b.compact();
b.flip();
int a = sc.write(b);
sc.close();
s.close();
System.out.println("wrote " + a);
客戶:
Charset charset = Charset.forName("ISO-8859-1");
SocketChannel sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1024));
sc.configureBlocking(true);
ByteBuffer b = ByteBuffer.allocate(32);
int a = sc.read(b);
sc.close();
b.flip();
CharBuffer c = charset.decode(b);
System.out.println("Got " + c);
爲什麼在將數據發送到客戶端之前在服務器端使用'b.flip()'?在閱讀數據之前還要在客戶端......? – 2013-02-26 17:15:47
我的理解是當你創建一個'ByteBuffer'或任何其他類型的'Buffer'時,它們都是以寫入模式開始的,所以你必須翻轉它們才能將它們置於讀取模式。否則,我不能正確理解這件事。 – Logan 2013-02-26 17:59:52