gpt4 book ai didi

java - 非阻塞回声服务器 - Java

转载 作者:行者123 更新时间:2023-11-30 11:10:01 25 4
gpt4 key购买 nike

这是一个 Echo 服务器。我不明白为什么在第一次与客户端连接后,即使在客户端关闭连接后服务器仍在打印“Reading..”和“Writing..”。服务器不应该用 select() 方法阻塞吗?谢谢

import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.io.IOException;

public class EchoServer
{
public static int DEFAULT_PORT=7;

public static void main(String [] args)
{

ServerSocketChannel serverChannel;
Selector selector;
try
{
serverChannel = ServerSocketChannel.open();
ServerSocket ss = serverChannel.socket();
InetSocketAddress address = new InetSocketAddress(DEFAULT_PORT);
ss.bind(address);
serverChannel.configureBlocking(false);
selector=Selector.open();
serverChannel.register(selector,SelectionKey.OP_ACCEPT);
} catch(IOException ex) {ex.printStackTrace(); return;}


while(true)
{
int selectednum=0;
try{
selectednum=selector.select(); //blocks
}catch (IOException ex) {ex.printStackTrace(); break;}
if (selectednum>0) {
Set<SelectionKey> readyKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key=iterator.next();
iterator.remove();
try{
if (key.isAcceptable()){
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel client = server.accept();
System.out.println("Accepted from "+client);
client.configureBlocking(false);
SelectionKey clientKey=client.register(
selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ);
ByteBuffer buffer = ByteBuffer.allocate(100);
clientKey.attach(buffer);
}
if (key.isReadable()){
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer output = (ByteBuffer) key.attachment();
System.out.println("Reading..");
client.read(output);
}
if (key.isWritable()){
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer output = (ByteBuffer) key.attachment();
output.flip();
System.out.println("Writing..");
client.write(output);
output.compact();
}
} catch (IOException ex) {
key.cancel();
try { key.channel().close();}
catch (IOException cex) {};
}
}
}
}
}
}

最佳答案

从客户端读取时,您没有检测到流结束。 read() 方法返回 -1。发生这种情况时,您应该关闭 channel 。

关于java - 非阻塞回声服务器 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27908709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com