java 判断tcp连接断开连接_检查Java TCP服务器上的客户端断开连接 – 仅输出

即使您的服务器没有从客户端“接收”,客户端套接字上的非阻塞读取也会告诉您无法读取任何内容(正如您所期望的那样),或者客户端已断开连接.

如果你正在使用NIO,你可以简单地使用一个非阻塞的选择器循环(带有非阻塞套接字),只能在你的30秒标记上写入.如果SelectionKey是可读的并且SocketChannel上的读取返回-1,则您知道客户端已断开连接.

编辑:阻止的另一种方法是简单地选择30秒超时.任何客户端断开连接都会导致select返回,您将通过读取集知道哪些是.您需要做的另外一件事是跟踪您在选择中被阻止的时间,以确定何时在30秒标记上进行写入(将下一个选择的超时设置为增量).

Big Edit:在与Myn交谈之后,提供完整的例子:

public static void main(String[] args) throws IOException {

ServerSocket serverSocket = null;

try {

serverSocket = new ServerSocket(4444);

} catch (IOException e) {

System.err.println("Could not listen on port: 4444.");

System.exit(1);

}

Socket clientSocket = null;

try {

clientSocket = serverSocket.accept();

} catch (IOException e) {

System.err.println("Accept failed.");

System.exit(1);

}

// Set a 1 second timeout on the socket

clientSocket.setSoTimeout(1000);

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

BufferedReader in = new BufferedReader(

new InputStreamReader(

clientSocket.getInputStream()));

long myNextOutputTime = System.currentTimeMillis() + 30000;

String inputLine = null;

boolean connected = true;

while (connected)

{

try {

inputLine = in.readLine();

if (inputLine == null)

{

System.out.println("Client Disconnected!");

connected = false;

}

}

catch(java.net.SocketTimeoutException e)

{

System.out.println("Timed out trying to read from socket");

}

if (connected && (System.currentTimeMillis() - myNextOutputTime > 0))

{

out.println("My Message to the client");

myNextOutputTime += 30000;

}

}

out.close();

in.close();

clientSocket.close();

serverSocket.close();

}

值得注意的是,PrintWriter确实让你远离实际的套接字,并且你不会在写入时捕获套接字断开连接(它永远不会抛出异常,你必须用checkError()手动检查它)您可以改为使用BufferedWriter(需要使用flush()来推送输出)并像BufferedReader一样处理它以捕获写入的disco.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值