Using Socket in Flutter apps?

前端 未结 3 1551
有刺的猬
有刺的猬 2020-12-16 22:23

I create a Flutter App. I need to connect my app to local network socket services. As shown below, I can use telnet Connect, Send data and Receive data from the server. I us

3条回答
  •  隐瞒了意图╮
    2020-12-16 22:53

    As attdona mentioned,

    Your server does not speak the websocket protocol but it exposes a plain tcp socket.

    So you need a TCP socket and there is a great tutorial on Sockets and ServerSockets which you can find here.

    Here's a snippet:

    import 'dart:io';
    import 'dart:async';
    
    Socket socket;
    
    void main() {
       Socket.connect("localhost", 4567).then((Socket sock) {
       socket = sock;
       socket.listen(dataHandler, 
          onError: errorHandler, 
          onDone: doneHandler, 
          cancelOnError: false);
       }).catchError((AsyncError e) {
          print("Unable to connect: $e");
       });
       //Connect standard in to the socket 
       stdin.listen((data) => socket.write(new String.fromCharCodes(data).trim() + '\n'));
    }
    
    void dataHandler(data){
       print(new String.fromCharCodes(data).trim());
    }
    
    void errorHandler(error, StackTrace trace){
       print(error);
    }
    
    void doneHandler(){
       socket.destroy();
    }
    

提交回复
热议问题