如何在Dart中使用RawSocket?

时间:2018-09-20 12:27:38

标签: java sockets socket.io dart flutter

我有服务器套接字,当我用java设置套接字时访问socket.setSoLinger(true,0);效果很好。我正在尝试用dart实现Java客户端代码,但我不断收到错误消息。同样,花费时间来获取错误。 Dart应该快!

在Java中,我以 socketOut = new DataOutPutStream(socket.getOutputStream());打开套接字。和socketIn = new DataInputStream(socket.getInputStream());

然后我可以使用 socketOut.write(queryStr.getBytes()); 进行写操作,并且我可以使用 response + = socketIn.readLine(); 进行阅读

在我的演示Dart项目中,我编写了以下代码,并不断收到以下错误。

错误:

Unhandled exception:
SocketException: OS Error: Broken pipe, errno = 32, address = ***.***.***.***, port = 48620
#0      _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:1112:29)
#1      _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#2      _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#3      _runPendingImmediateCallback (dart:isolate/runtime/libisolate_patch.dart:115:13)
#4      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:172:5)

Dart代码:

import 'package:untitled/untitled.dart' as untitled;
import 'dart:io';
import 'dart:async';

Socket socket;
String _dataToBeSent = "00802020N0307809491508590203000000000000490012001629   01700CD0";
var reply;

// TODO: MAIN
main(List<String> arguments) {

  _remoteServerConnect();

}

// TODO: REMOTE SERVER  CONNECT
void _remoteServerConnect() async {
  try {
      var socket = await Socket.connect('***.***.***.***', *****);
      socket.writeln('$_dataToBeSent\n');

      await for (var data in socket) {
        reply = new String.fromCharCodes(data).trim();
        print("reply: $reply");

        socket.close();
        socket.destroy();
      } // await socket

      socket.handleError((data) {
        print("error: $data");
      });

  } on Error catch (e) {
    print(e.toString());
  } on Exception catch (f) {
    print(f.toString());
  }
}

我不确定。但是有些事情告诉我,我必须使用RawSocket。我的问题是如何在Dart中使用RawSocket?

UPDATE-1::阅读链接后,我设法重新编码我的套接字,如下所示。但是这次我遇到了socket.write错误。

// TODO: REMOTE SERVER  CONNECT
void _remoteServerConnect()  {
  Socket.connect('***.***.***.***', *****).then((Socket sock) {
    socket = sock;
    socket.listen(dataHandler,
        onError: errorHandler,
        onDone: doneHandler,
        cancelOnError: false);
  }).catchError((AsyncError e) {
    print("Unable to connect: $e");
    exit(1);
  });

  print(_dataToBeSent);
  socket.write(_dataToBeSent);
}

void dataHandler(data){
  print(new String.fromCharCodes(data).trim());
}

void errorHandler(error, StackTrace trace){
  print(error);
}

void doneHandler(){
  socket.destroy();
  exit(0);
}

“ socket.write(_dataToBeSent);”中出现错误行说方法'write'在null上被调用。

00802020N0307809491508590203000000000000490012001629   01700CD0
Unhandled exception:
NoSuchMethodError: The method 'write' was called on null.
Receiver: null
Tried calling: write(""00802020N0307809491508590203000000000000490012001629   01700CD0"")
#0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:48:5)
#1      _remoteServerConnect (file:///home/capital/IdeaProjects/untitled/bin/main.dart:31:10)
#2      main (file:///home/capital/IdeaProjects/untitled/bin/main.dart:13:3)
#3      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:287:32)
#4      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)

UPDATE-2::如果我使用Future,则看不到任何数据,但数据运行无误。

// TODO:远程服务器连接

Future _remoteServerConnect() async {
  await Socket.connect('***.***.***.***', ******).then((Socket sock) {
    socket = sock;
    socket.listen(dataHandler,
        onError: errorHandler,
        onDone: doneHandler,
        cancelOnError: false);
  }).catchError((AsyncError e) {
    print("Unable to connect: $e");
    exit(1);
  });

  print(_dataToBeSent);
  await socket.write(_dataToBeSent);
}

void dataHandler(data){
  print(new String.fromCharCodes(data).trim());
}

void errorHandler(error, StackTrace trace){
  print(error);
}

void doneHandler(){
  socket.destroy();
  exit(0);
}

结果:

00802020N02018092108262302030000000000005494490012001629   00000000
Process finished with exit code 0

1 个答案:

答案 0 :(得分:0)

不确定它是否仍然相关,但代码中存在潜在错误。与其尝试在 socket = sock 的回调中设置 connect,不如将其设置为 connect 方法返回的等待值。

Future _remoteServerConnect() async {
  socket = await Socket.connect('***.***.***.***', ******).then((Socket sock) {
    sock.listen(dataHandler,
        onError: errorHandler,
        onDone: doneHandler,
        cancelOnError: false);
  }).catchError((AsyncError e) {
    print("Unable to connect: $e");
    exit(1);
  });

  print(_dataToBeSent);
  await socket.write(_dataToBeSent);
}

void dataHandler(data){
  print(new String.fromCharCodes(data).trim());
}

void errorHandler(error, StackTrace trace){
  print(error);
}

void doneHandler(){
  socket.destroy();
  exit(0);
}