这是我尝试过的:
服务器:
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:在 Vishal 的帮助下,我们终于有了一个可行的解决方案:
服务器:
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);