如何连接插座?

时间:2018-06-02 15:35:21

标签: sockets dart flutter

如何连接到套接字,我将Python脚本编写为服务器,这个服务器端是这样的:

import socket
import time


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("192.168.0.113", 9999))# 注意bind的这里,IP地址和端口号都要与前面的程序中一样
sock.listen(2)# 监听端口

# 等待数据源端连接
src, src_addr = sock.accept()
print "Source Connected by", src_addr

# 等待目标端连接
dst, dst_addr = sock.accept()
print "Destination Connected by", dst_addr

while True:
    msg = src.recv(1024 *1024)
    if not msg:
        break
    try:
        dst.sendall(msg)
    except Exception as ex:
        dst, dst_addr = sock.accept()
        print "Destination Connected Again by", dst_addr
    except KeyboardInterrupt:
        print "Interrupted"
        break

src.close()
dst.close()

我想用Flutter编写一个非常简单的客户端来显示从这个python服务器通过socket发送的图像,如何实现这个目标?

1 个答案:

答案 0 :(得分:1)

我不知道原始套接字,但如果你可以在Python中使用WebSockets,你可以使用web_socket_channel包:

import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/status.dart' as status;

main() async {
  var channel = await IOWebSocketChannel.connect("ws://localhost:1234");

  channel.stream.listen((message) {
    channel.sink.add("received!");
    channel.close(status.goingAway);
  });
}

这里有更多关于使用它的信息:

https://flutter.io/cookbook/networking/web-sockets/