一、定界符成帧
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编程学习--基于定界符的成帧详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
查看更多关于详解Java的TCP/IP编程学习--基于定界符的成帧的详细内容...