本问题来自云栖社区【阿里Java技术进阶2群】。https://yq.aliyun.com/articles/690084 点击链接欢迎加入社区大社群。
用while()循环不断接受和发送,要用线程啊记得。。。然后添加事件响应 关闭程序就调用socket.close()
基本上来说的,socker连接,服务始终运行,是都通while(true)
不管是BIO还是NIO,其实都是通过轮训的方式来实现socket服务的。下面几个demo或许有助于你:
public class BIODemo {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("0.0.0.0", 8888), 50);
Socket socket;
while ((socket = serverSocket.accept()) != null) {
InputStream is = socket.getInputStream();
byte[] data = new byte[1024];
is.read(data);
System.out.println(new String(data, UTF_8));
OutputStream out = socket.getOutputStream();
out.write(data);
socket.close();
}
}
}
public class NIODemo {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress("0.0.0.0", 8888), 50);
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (!key.isValid()) {
continue;
}
if (key.isAcceptable()) {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel clientChannel = serverChannel.accept();
clientChannel.configureBlocking(false);
clientChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
ByteBuffer buffer = ByteBuffer.wrap(new byte[1024]);
SocketChannel clientChannel = (SocketChannel) key.channel();
int read = clientChannel.read(buffer);
if (read == -1) {
key.cancel();
clientChannel.close();
} else {
buffer.flip();
clientChannel.write(buffer);
}
}
}
iterator.remove();
}
}
}
如果你需要更详细的更深入的了解,可以参考我的这篇文章 JAVA中BIO、NIO、AIO的分析理解 https://developer.aliyun.com/article/726698?spm=a2c6h.13148508.0.0.1d844f0eaWNdWj
while(true){
Socket socket=serverSocket.accept();
new Thread(new MyRuns(socket)).start();
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。