Dart UDP 客户端/服务器 [英] Dart UDP client/server

查看:58
本文介绍了Dart UDP 客户端/服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 RawDatagramSocket 来实现 udp 客户端,但我有点卡住了.我既不能发送也不能接收任何数据.据我所知,这是 Dart 中的一个非常新的功能,除了 tcp 之外我找不到任何示例.

I've been trying to implement a udp client by using the RawDatagramSocket but I'm kind of stuck. I can neither send or receive any data. It's a pretty new feature in Dart as far as I know and I can't find any examples except for tcp.

另外,我不知道是否有错误或什么,但似乎我只能绑定到本地主机.尝试绑定到另一台计算机 IPV4 地址时,我收到一个套接字异常(由于某些无效的 IP 地址而无法创建数据报套接字).我已经尝试过 tcp 套接字,将数据连接并发送到用 c# 实现的 tcp 服务器(而 dart 代码在 Mac OS 上运行),没有问题.

Also, I don't know if there is a bug or anything, but it seems like I can only bind to the localhost. When trying to bind to another computer IPV4 address, I receive a socket exception (failure to create datagram socket due to some invalid IP address). I've tried the tcp socket, connecting and sending data to a tcp server implemented in c# (while the dart code was running on Mac OS), without a problem.

有谁做过这方面的工作并且可以提供一个很好的例子吗?

Anyone who has worked on it and can provide a nice example?

我的代码:

import 'dart:io';
import 'dart:convert';

void main() {
  var data = "Hello, World";
  var codec = new Utf8Codec();
  List<int> dataToSend = codec.encode(data);
  //var address = new InternetAddress('172.16.32.73');
  var address = new InternetAddress('127.0.0.1');
  RawDatagramSocket.bind(address, 16123).then((udpSocket) {
    udpSocket.listen((e) {
      print(e.toString());
      Datagram dg = udpSocket.receive();
      if(dg != null) 
        dg.data.forEach((x) => print(x));

    });
    udpSocket.send(dataToSend, new InternetAddress('172.16.32.73'), 16123);
    print('Did send data on the stream..');
  });
}

编辑

忙了几天,但是在更彻底地阅读了 API 规范之后,在下面评论的帮助下,我了解到,由于它是一次性侦听器,因此每次发送都必须将 writeEventsEnabled 设置为 true.考虑到 Günter、Fox32 和 Tomas 的评论,其余更改非常简单.

Been busy for a couple of days but after reading the API spec more thoroughly, and with some help from the comments below, I learned that, since it's a one-shot listener, the writeEventsEnabled must be set to true for every send. The rest of the changes are pretty straightforward given the comments by Günter, Fox32 and Tomas.

我尚未测试将其设置为服务器,但我认为这只是绑定到首选端口的问题(而不是下面示例中的 0).服务器在 Windows 8.1 上用 C# 实现,而 Dart VM 在 Mac OS X 上运行.

I haven't tested to set it up as a server yet but I assume that's just a matter of binding to the preferred port (instead of 0 as in the example below). The server was implemented in C# on a Windows 8.1, while the Dart VM was running on Mac OS X.

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

void connect(InternetAddress clientAddress, int port) {
  Future.wait([RawDatagramSocket.bind(InternetAddress.ANY_IP_V4, 0)]).then((values) {
    RawDatagramSocket udpSocket = values[0];
    udpSocket.listen((RawSocketEvent e) {
      print(e);
      switch(e) {
        case RawSocketEvent.READ :
          Datagram dg = udpSocket.receive();
          if(dg != null) {
            dg.data.forEach((x) => print(x));
          }
          udpSocket.writeEventsEnabled = true;
          break;
        case RawSocketEvent.WRITE : 
          udpSocket.send(new Utf8Codec().encode('Hello from client'), clientAddress, port);
          break;
        case RawSocketEvent.CLOSED : 
          print('Client disconnected.');
      }
    });
  });
}

void main() {
  print("Connecting to server..");
  var address = new InternetAddress('172.16.32.71');
  int port = 16123;
  connect(address, port);
}

推荐答案

我不知道这是否是正确的方法,但它对我有用.

I don't know if this is the right way to do it, but it got it working for me.

import 'dart:io';
import 'dart:convert';

void main() {
  var data = "Hello, World";
  var codec = new Utf8Codec();
  List<int> dataToSend = codec.encode(data);
  var addressesIListenFrom = InternetAddress.anyIPv4;
  int portIListenOn = 16123; //0 is random
  RawDatagramSocket.bind(addressesIListenFrom, portIListenOn)
    .then((RawDatagramSocket udpSocket) {
    udpSocket.forEach((RawSocketEvent event) {
      if(event == RawSocketEvent.read) {
        Datagram dg = udpSocket.receive();
        dg.data.forEach((x) => print(x));
      }
    });
    udpSocket.send(dataToSend, addressesIListenFrom, portIListenOn);
    print('Did send data on the stream..');
  });
}

这篇关于Dart UDP 客户端/服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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