一、定界符成幀
framer接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package framer; import java.io.ioexception; import java.io.outputstream; public interface framer { /** * 添加成幀信息并將指定消息輸出到指定流 * @param message * @param out * @throws ioexception */ void framemsg( byte [] message, outputstream out) throws ioexception; /** * 掃描指定的流,從中抽取下一條信息 * @return * @throws ioexception */ byte [] nextmsg() throws ioexception; } |
基于定界符的成幀
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
50
51
52
53
54
55
56
57
58
|
package framer; import java.io.*; /** * @classname delimframer * @description todo * @author cays * @date 2019/3/16 22:04 * @version 1.0 **/ public class delimframer implements framer { //輸入流 private inputstream in; //定界符為換行符 private static final byte delimiter= '\n' ; public delimframer(inputstream in) { this .in = in; } @override public void framemsg( byte [] message, outputstream out) throws ioexception { //檢測信息中是否包含換行符 for ( byte b:message){ if (b==delimiter){ throw new ioexception( "message contaions delimiter" ); } } //將成幀的信息輸出到流中 out.write(message); //添加定界符 out.write(delimiter); out.flush(); } @override public byte [] nextmsg() throws ioexception { bytearrayoutputstream messagebuffer= new bytearrayoutputstream(); int nextbyte; //讀取流中的每一個字節,直到遇到定界符 while ((nextbyte=in.read())!=delimiter){ if (nextbyte==- 1 ){ //如果遇到定界符之前就到了流的終點 if (messagebuffer.size()== 0 ){ return null ; } else { //如果存入緩存區之前有數據,拋出異常 throw new eofexception( "non-empty message without delimiter" ); } } //將無定界符的字節寫入消息緩存區 messagebuffer.write(nextbyte); } //將消息緩存區的內容以字節數組的形式返回 return messagebuffer.tobytearray(); } } |
以上所述是小編給大家介紹的java的tcp/ip編程學習--基于定界符的成幀詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!