📄 jremabstractprotocol.java
字号:
/* * JRemCntl - Copyright (C) 2007 Filippo Di Vattimo <fildiv@gmail.com> * See COPYING */package fildiv.jremcntl.common.proto;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public abstract class JRemAbstractProtocol { // size protected final static int LENGHT_INT = 4; protected final static int LENGHT_SHORT = 2; private final static int HEADER_SIZE = LENGHT_INT * 2; private InputStream in; private OutputStream out; public JRemAbstractProtocol(InputStream in, OutputStream out) { this.in = in; this.out = out; } public InputStream getInputStream() { return in; } public boolean isClosed() { return in == null; } public void close() { if (isClosed()) return; try { if (in != null) { synchronized (in) { in.close(); } in = null; } if (out != null) { synchronized (out) { out.close(); } out = null; } } catch(Exception e) { } } protected void createMessage(ByteWriter bw, int size, int type) { bw.setBytes(newMessageBuffer(size)); addHeader(bw, type, size); } protected void addHeader(ByteWriter bw, int type, int size) { bw.addInt(size + LENGHT_INT); bw.addInt(type); } protected byte[] newMessageBuffer(int size) { int packetSize = HEADER_SIZE + size; byte []data = new byte[packetSize]; return data; } protected ByteReader readPacket(boolean lockThread) throws IOException { if (!lockThread) { if (in.available() == 0) return null; } byte[] lengthBuf = new byte[LENGHT_INT]; readFully(in, lengthBuf); ByteReader br = new ByteReader(); br.setBytes(lengthBuf); int length = br.getInt(); byte[] bytes = new byte[length]; readFully(in, bytes); br.setBytes(bytes); return br; } protected void sendMessage(byte[] message) throws JRemDataTransferException { if (isClosed()) throw new JRemDataTransferException( "Unable to send message, connection doesn't exist!"); try { synchronized(out) { out.write(message); out.flush(); } } catch (IOException e) { throw new JRemDataTransferException(e); } } protected void readFully(InputStream in, byte[] buffer) throws IOException { int bytesRead = 0; while (bytesRead < buffer.length) { int count = in.read(buffer, bytesRead, buffer.length - bytesRead); if (count == -1) throw new IOException("Input stream closed"); bytesRead += count; } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -