使用netty可以很简单的进行分包。
本文介绍一种使用JDK自带方法进行分包,支持Java或者Android端。
适用于socket、蓝牙、wifi通信。
接收端正常收到两个数据包,即没有发生拆包和粘包的现象,此种情况不用做特殊处理。
接收端只收到一个数据包,包含了两个或者多个数据包,这种现象即为粘包,需要手动拆分。
一个数据包被拆分成多次发送,每次收到的都是不完整的数据包,这种称为拆包,需要手动组合。
拆包和沾包同时发生,比如发送两个数据包aaa和bbb,接收端收到两个数据包aa,abbb。
public static void main(String[] args) {
String hostname = "127.0.0.1";
int port = 5209;
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
writer.println("Hello,I am client");
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
复制代码
public static void main(String[] args) {
String hostname = "127.0.0.1";
int port = 5209;
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
writer.println("Hello,I am client");
InputStream input = socket.getInputStream();
Scanner scan = new Scanner(input);
scan.useDelimiter(new String(new byte[]{0x03}));
while (scan.hasNext()) {
String line = scan.next();
System.out.println(line);
}
} catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
复制代码