Java的TCP/IP编程学习--基于定界符的成帧

一、定界符成帧

Framer接口

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;
}

基于定界符的成帧

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();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39400984/article/details/88697835