请问这个java.nio的例子哪里错了?
直接上代码。
client端:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class JavaTest {
public static void main(String[] args) throws Exception {
SocketChannel client = SocketChannel.open();
client.connect(new InetSocketAddress("127.0.0.1", 30003));
ByteBuffer buffer = ByteBuffer.allocate(1024);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String console = null;
byte[] bytes = new byte[1024];
while ((console = bufferedReader.readLine()) != null) {
buffer.clear();
buffer.put(console.getBytes(), 0, console.getBytes().length);
int n = client.write(buffer);
System.out.println("Client write: " + n);
buffer.flip();
n = client.read(buffer);
System.out.println("Client read: " + n);
buffer.get(bytes, 0, n);
buffer.flip();
System.out.println(new String(bytes));
}
client.close();
}
}
server端代码:
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class Test {
public static void main(String args[]) throws Exception
{
ServerSocketChannel server = ServerSocketChannel.open();
server.socket().bind(new InetSocketAddress("127.0.0.1", 30003));
Selector selector = Selector.open();
server.configureBlocking(false);
SelectionKey skey = server.register(selector, SelectionKey.OP_ACCEPT);
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
selector.select();
Set<SelectionKey> result = selector.selectedKeys();
Iterator<SelectionKey> resultIterator = result.iterator();
while (resultIterator.hasNext()) {
SelectionKey eachone = (SelectionKey)resultIterator.next();
//if server has an acceptable client
if (eachone.isAcceptable()) {
ServerSocketChannel acceptChannel = (ServerSocketChannel)eachone.channel();
//new client
SocketChannel client = acceptChannel.accept();
client.configureBlocking(false);
SelectionKey clientkey = acceptChannel.register(selector, SelectionKey.OP_READ);
} else if (eachone.isReadable()) {
SocketChannel client = (SocketChannel)eachone.channel();
//readable client
byte[] bytes = new byte[1024];
buffer.clear();
int n = client.read(buffer);
System.out.println("Server read: " + n);
buffer.flip();
buffer.get(bytes, 0, n);
System.out.println(new String(bytes));
buffer.flip();
n = client.write(buffer);
System.out.println("Server write: " + n);
client.close();
}
resultIterator.remove();
}
}
}
}
client端从System.in读入一行字符,write到server端,再从server端read,将server端发回来的字符串输出到System.out上。
调式时出错了,求问为什么。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你也不把出错信息发一下?