如何处理Dart中的插座断开连接? [英] How to handle socket disconnects in Dart?

查看:96
本文介绍了如何处理Dart中的插座断开连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在服务器上使用Dart 1.8.5。
我想实现TCP套接字服务器,它侦听传入的连接,向每个客户端发送一些数据,并在客户端断开连接时停止生成数据。

I'm using Dart 1.8.5 on server. I want to implement TCP Socket Server that listens to incoming connections, sends some data to every client and stops to generate data when client disconnects.

这里是示例代码

void main() {
  ServerSocket.bind(
      InternetAddress.ANY_IP_V4,
      9000).then((ServerSocket server) {
    runZoned(() {
      server.listen(handleClient);
    }, onError: (e) {
      print('Server error: $e');
    });
  });
}

void handleClient(Socket client) {
  client.done.then((_) {
    print('Stop sending');
  });
  print('Send data');
}

此代码接受连接并打印发送数据。但是,即使客户端消失了,它也永远不会打印停止发送。

This code accepts connections and prints "Send data". But it will never print "Stop sending" even if client was gone.

问题是:如何在监听器中捕获客户端断开连接?

The question is: how to catch client disconnect in listener?

推荐答案

套接字是双向的,即它具有输入流和输出接收器。当通过调用 Socket.close()

A Socket is bidirectional, i.e. it has an input stream and an output sink. The Future returned by done is called when the output sink is closed by calling Socket.close().

如果要在输入流关闭时收到通知,请尝试使用 Socket.drain()

If you want to be notified when the input stream closes try using Socket.drain() instead.

请参见下面的示例。您可以使用telnet进行测试。当您连接到服务器时,它将发送字符串 Send。每一秒。当您关闭telnet时(ctrl-],然后键入close。服务器将显示停止。

See the example below. You can test it with telnet. When you connect to the server it will send the string "Send." every second. When you close telnet (ctrl-], and then type close). The server will print "Stop.".

import 'dart:io';
import 'dart:async';

void handleClient(Socket socket) {

  // Send a string to the client every second.
  var timer = new Timer.periodic(
      new Duration(seconds: 1), 
      (_) => socket.writeln('Send.'));

  // Wait for the client to disconnect, stop the timer, and close the
  // output sink of the socket.
  socket.drain().then((_) {
    print('Stop.');    
    timer.cancel();
    socket.close();
  });
}

void main() {
  ServerSocket.bind(
      InternetAddress.ANY_IP_V4,
      9000).then((ServerSocket server) {
    runZoned(() {
      server.listen(handleClient);
    }, onError: (e) {
      print('Server error: $e');
    });
  });
}

这篇关于如何处理Dart中的插座断开连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆