⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 socketio.java

📁 一个实用工具类
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
		// fill the buffer		while (true) {			// if we have to stop reading if we got a pattern of bytes			// and if this condidion is true then stop reading.			if ((pattern != null) && totalReadBytes > 0) {				if (f_patternNextByteToCheck > 0) {					// we have found the begining of the pattern in the previous					// read. So, search the rest of the pattern in this read starting					// at the begining of the buffer.					int startPattern =						totalReadBytes							- pattern.length							+ f_patternNextByteToCheck;					if (0 > startPattern) {						startPattern = 0;					}										f_patternEndOffset =						indexOfEndOfPattern(							buf,							(pattern.length - f_patternNextByteToCheck),							pattern,							startPattern);					if (f_patternEndOffset < 0) {						f_patternNextByteToCheck = 0;					}				}				if ((f_patternEndOffset < 0)					&& (f_patternNextByteToCheck <= 0)) {					// no pattern found (not continued from the previous read)					// or it is a new search. Search at the end.					// calculate the position in buffer to start searching the pattern.					int bufferPatternSerachOffset = 0;					if (totalReadBytes >= patternSearchOffsetFromTheEnd) {						bufferPatternSerachOffset =							totalReadBytes - patternSearchOffsetFromTheEnd;					}					f_patternEndOffset =						indexOfEndOfPattern(							buf,							totalReadBytes,							pattern,							bufferPatternSerachOffset);				}				// pattern found?				if (f_patternEndOffset > -1) {					if ((f_patternEndOffset + 1) < (offset + totalReadBytes)) {						/*						 * keep after pattern bytes for next read.						 * Adjust total read bytes to reflect the total bytes						 * until the pattern's end only.						 */						byte[] nr =							new byte[(offset + totalReadBytes)								- (f_patternEndOffset + 1)];						System.arraycopy(							buf,							(f_patternEndOffset + 1),							nr,							0,							nr.length);						totalReadBytes = totalReadBytes - nr.length;						if (f_nextRead == null) {							f_nextRead = nr;						} else {							/*							 * Concatenate exceeded bytes with previous							 * exceeded bytes. This chunk cames from that previous							 * exceeded bytes then we reput some bytes in the begining							 * for next read.							 */							byte[] anr =								new byte[f_nextRead.length + nr.length];							System.arraycopy(nr, 0, anr, 0, nr.length);							System.arraycopy(								f_nextRead,								0,								anr,								nr.length + 1,								f_nextRead.length);							f_nextRead = anr;						}					} else {						f_nextRead = null;					}					break;				}			}			// if the buffer are filled then stop reading.			if (totalReadBytes >= count) {				break;			}			// how much bytes to read?			int rest = count - totalReadBytes;			int size = (f_chunkSize < rest ? f_chunkSize : rest);			// how much time to wait?			long restTime =				f_bufferReadWriteTimeout					- (System.currentTimeMillis() - startTime);			if (restTime <= 0) {				Log.logStr(					Log.LOG_LEVEL_LOW,					this,					Log.LOG_TYPE_INFO,					"readBytes(byte[], int, int, byte[], int)",					"Timed out filling the buffer!");				break;			}			int readTimeout =				new Long(					(f_chunkReadTimeout < restTime						? f_chunkReadTimeout						: restTime))					.intValue();			try {				int oneReadCount =					readBytes(						buffer,						offset + totalReadBytes,						size,						readTimeout);				if (Log.shouldLog(CLASS_NAME, Log.LOG_LEVEL_FULL)) {					Log.logStr(						this,						Log.LOG_TYPE_INFO,						"readBytes(byte[], int, int, byte[], int)",						(oneReadCount > 0							? "read "								+ oneReadCount								+ " bytes ["								+ new String(									buffer.array(),									offset + totalReadBytes,									oneReadCount)								+ "]"							: "readBytes returned " + oneReadCount));				}				if (oneReadCount > 0) {					totalReadBytes += oneReadCount;				} else if (oneReadCount < 0) {					// reached end of file!					Log.logStr(						this,						Log.LOG_TYPE_INFO,						"readBytes(byte[], int, int, byte[], int)",						"Reached end of file!");					close();					break;				}			} catch (InterruptedIOException e) {				// OK will retry				isReadChunckTimedout = true;			} catch (IOException e) {				Log.logStr(					this,					Log.LOG_TYPE_ERROR,					"readBytes(byte[], int, int, byte[], int)",					e.getMessage());				close();				throw e;			}		}		if (Log.shouldLog(this.getClass().getName(), Log.LOG_LEVEL_LOW)) {			Log.logStr(				this,				Log.LOG_TYPE_INFO,				"readBytes(byte[], int, int, byte[], int)",				"read buffer: "					+ (f_noLog ? "<data>" : new String(buffer.array())));		}		// if no timeout occured and there zero bytes read		// then mark socket unsane.		if (totalReadBytes == 0) {			if (isReadChunckTimedout) {				throw new ReadTimeoutException();			} else {				close();			}		}		return totalReadBytes;	}	/**	 * Find a pattern of bytes in a buffer of bytes. return the position of	 * the end of the pattern in buffer.	 * NOTE: pattern of bytes must not contain repetitive sequences	 * 	of bytes. in this case the search my not be successful every time.	 * 	 * @param buffer byte[], buffer of bytes where to search the pattern.	 * @param count int, number of bytes to serach in the buffer starting from 0.	 * @param pattern byte[], pattern of bytes to search for.	 * @param offset int, start searching in buffer at this offset.	 * 	 * @return int, -1 if pattern not found, index of startup of the pattern in 	 * 		buffer otherwise.	 */	protected int indexOfEndOfPattern(		byte[] buffer,		int count,		byte[] pattern,		int offset) {		int pos = -1;		boolean found;		if (buffer == null || pattern == null) {			f_patternNextByteToCheck = 0;			return -1;		}		if (count > buffer.length) {			// can't search outside buffer's data.			f_patternNextByteToCheck = 0;			return -1;		}		int patternLen = pattern.length;		int nextToCheckInBuffer = -1;		for (int s = offset; s < count; s++) {			// Assume that we found it.			found = true;			if (buffer[s] == pattern[f_patternNextByteToCheck]) {				// first byte match! check the rest.				int j = 0;				for (j = f_patternNextByteToCheck; j < patternLen; j++) {					nextToCheckInBuffer = s + j - f_patternNextByteToCheck;					if (nextToCheckInBuffer >= count) {						// reach end of buffer but still pattern bytes to						// check! May be theses bytes will match in the begining						// of next read buffer. Keep index of next byte in pattern						// to check with the position zero of next read buffer.						found = false;						f_patternNextByteToCheck = j;						if (Log							.shouldLog(								this.getClass().getName(),								Log.LOG_LEVEL_MEDIUM)) {							Log.logStr(								this,								Log.LOG_TYPE_INFO,								"indexOfEndOfPattern()",								"End of buffer reached at=["									+ nextToCheckInBuffer									+ "], count=["									+ count									+ "], offset=["									+ offset									+ "], patternLen=["									+ patternLen									+ "], f_patternNextByteToCheck=["									+ f_patternNextByteToCheck									+ "], nextToCheckInBuffer=["									+ nextToCheckInBuffer									+ "], s=["									+ s									+ "], j=["									+ j									+ "], buffer=["									+ (f_noLog										? "<data>"										: new String(											buffer,											offset,											count - offset))									+ "].");						}						break;					} else if (buffer[nextToCheckInBuffer] != pattern[j]) {						if (Log							.shouldLog(								this.getClass().getName(),								Log.LOG_LEVEL_MEDIUM)) {							Log.logStr(								this,								Log.LOG_TYPE_INFO,								"indexOfEndOfPattern()",								"NOT Found f_patternNextByteToCheck = 0.");						}						// here is a different byte in the pattern.						found = false;						f_patternNextByteToCheck = 0;						break;					}				}				if (found) {					// found the pattern.					// return its end index in the buffer.					if (Log						.shouldLog(							this.getClass().getName(),							Log.LOG_LEVEL_MEDIUM)) {						Log.logStr(							this,							Log.LOG_TYPE_INFO,							"indexOfEndOfPattern()",							"Found pattern at=["								+ nextToCheckInBuffer								+ "], count=["								+ count								+ "], offset=["								+ offset								+ "], patternLen=["								+ patternLen								+ "], f_patternNextByteToCheck=["								+ f_patternNextByteToCheck								+ "], nextToCheckInBuffer=["								+ nextToCheckInBuffer								+ "], s=["								+ s								+ "], j=["								+ j								+ "], buffer=["								+ (f_noLog ? "<data>" : new String(buffer))								+ "].");					}					f_patternNextByteToCheck = 0;					return nextToCheckInBuffer;				}			}		}		return -1;	}	/**	 * write an array of bytes onto the socket.	 * 	 * @param buffer byte[], buffer to write	 * 	 * @return boolean, write success status.	 */	public void write(byte[] buffer) throws IOException {		Log.logStr(			Log.LOG_LEVEL_LOW,			this,			Log.LOG_TYPE_INFO,			"write(byte[])",			"writing ...");		if (buffer == null) {			throw new IOException("Got NULL buffer to write");		}		this.write(buffer, 0, buffer.length);	}	/**	 * write an array of bytes onto the socket.	 * 	 * @param buffer byte[], buffer to write	 * @param offset int, starting byte in the array	 * @param count int, number of bytes to write	 * 	 * @return boolean, write success status.	 */	public void write(byte[] buf, int offset, int count) throws IOException {		// work on copy of socket and input stream.		// if socket are closed after our null test on it		// we will catch it in the exception block		// instead of having a NullPointer...		Log.logStr(			Log.LOG_LEVEL_MEDIUM,			this,			Log.LOG_TYPE_INFO,			"write(byte[], int, int)",			"writing ...");		if (buf == null) {			throw new IOException("Got NULL buffer to write");		}		ByteBuffer buffer = ByteBuffer.wrap(buf);		if (Log.shouldLog(this.getClass().getName(), Log.LOG_LEVEL_FULL)) {			Log.logStr(				this,				Log.LOG_TYPE_INFO,				"write(byte[], int, int)",				"writing buffer(offset="					+ offset					+ ", count="					+ count					+ "): "					+ (f_noLog ? "<data>" : new String(buffer.array())));		}		// catch IOException internally to manage internal state.		// then forward exception to caller.				try {			writeBytes(buffer, offset, count, f_bufferReadWriteTimeout);		} catch (IOException e) {			Log.logStr(				Log.LOG_LEVEL_LOW,				this,				Log.LOG_TYPE_ERROR,

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -