# Dart Socket之TCP粘包

# 什么是TCP粘包

socket编程-tcp粘包

# dart中的socket

  • RawDatagramSocket

    ​ 用于UDP通信

* RawServerSocket、RawSocket、ServerSocket、Socket

​	RawServerSocket,RawSocket:低级别的tcp服务提供类,可用于IP,ICMP协议		
​	ServerSocket、Socket:用于TCP通信
  • RawSecureServerSocket,RawSecureSocket、SecureServerSocket、SecureSocket

    ​ 支持SSL、TSL的安全通信

# dart之udp通信

udp是无状态通信,通常用于服务发现。
//Server端
var udpSocket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 34343);
//这里要启用广播,重要
udpSocket.broadcastEnabled = true;
await for (var event in udpSocket) {
    if (RawSocketEvent.read == event) {
        var data = udpSocket.receive();
        var result = Utf8Codec().decode(data.data);
        print(result);
    }
}
//Client端
//要创建一个udp实例,必须指定一个端口,即使仅为客户端,端口任意
var client = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 33333);
client.broadcastEnabled = true;
var helloBytes = utf8.encode("hello");
Future.doWhile(() async {
    await Future.delayed(Duration(seconds: 1));
    udpSocket.send(helloBytes, InternetAddress("255.255.255.255"), 34343);
    return true;
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# dart之tcp通信

//Server端
main(List<String> args) async {
  var server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 33333);
  print("start server....");
  await for (var socket in server) {
    acceptSocket(socket);
  }
}
//接受Client连接
acceptSocket(Socket socket) async {
  await for (var data in socket) {
    print("server:$data");
    send(socket, data);
  }
}
send(Socket socket, data) async {
  sleep(Duration(seconds: 3));
  try {
    socket.add(data);
    await socket.flush();
  } catch (e) {
    print(e);
  }
}
//Client端
main(List<String> args) async {
  var client = await Socket.connect(InternetAddress.loopbackIPv4, 33333);
  var helloBytes = utf8.encode("hello");
  client.add(helloBytes);
  await client.flush();
  await for (var data in client) {
    print("clinet:$data");
    send(client, data);
  }
}
send(Socket socket, data) async {
  sleep(Duration(seconds: 3));
  try {
    socket.add(data);
    await socket.flush();
  } catch (e) {
    print(e);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

# dart之tcp粘包扩展

最近写了一个文件传输工具需要对tcp进行粘包处理,所以实现了几个tcp粘包处理类。

package: d_socket