socket 读、写字节流数据

socket是网络通信套接字。主要体现在读与写方面。 ( 阻塞读)

C版本:

int ReadFile(int nFile, void * pData, int * pSize)
{
	int nLeft, nRead;
	char *pcData = pData;
	ASSERT(pData != NULL && pSize != NULL);
	nLeft = *pSize;
	while (nLeft > 0)
	{
		if ((nRead = read(nFile, pcData, nLeft)) < 0)
		{
			if (errno != EINTR)
				ASSERT(0);
			nRead = 0;
		}
		else if (nRead == 0)
			break;
		nLeft -= nRead;
		pcData += nRead;
	}
	*pSize = *pSize - nLeft;
	return 0;
}
int WriteFile(int nFile, void* pData, int nSize)
{
	int nLeft = nSize, nWrite;
	const char *pcData = pData;
	ASSERT(pData != NULL);
	while (nLeft > 0)
	{
		if ((nWrite = write(nFile, pcData, nLeft)) <= 0)
		{
			if (errno != EINTR)
				ASSERT(0);
			nWrite = 0;
		}
		nLeft -= nWrite;
		pcData += nWrite;
	}
	return 0;
}
JAVA版本:

	public static String sendSocket(String ip, int port, String param) {

		Socket socket = null;
		String rspStr = null;
		try {
			String reqStr = String.format("%04d%s", param.length(), param);
			LOGGER.info("发送数据:" + reqStr);

			socket = new Socket(ip, port);
		
			OutputStream outPutStream = socket.getOutputStream();
			outPutStream.write(reqStr.getBytes());
			outPutStream.flush();

			socket.setSoTimeout(60*1000);  //设置读超时时间 毫秒
			InputStream inputStream = socket.getInputStream();
			
			//4字节长度域
			byte[] lenbuf = new byte[4];
			inputStream.read(lenbuf);
			int count = Integer.valueOf(new String(lenbuf));
			byte[] buf = new byte[count];
			LOGGER.info("count====" + count);

			//内容域
			int readCount = 0;
			while (readCount < count) {
				readCount += inputStream.read(buf, readCount, count - readCount);
			}
			rspStr = new String(buf);
			LOGGER.info("收到响应" + rspStr);

			socket.close();
			return rspStr;

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LOGGER.error("异常出错", e);

		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					LOGGER.error("异常出错", e);
				}
			}
		}

		return rspStr;

	}

  • java读取内容时, 内容很多时,低层并不会一次全都读出,需要进行多次读。
  • 参考:应用 http://blog.csdn.net/zhuxiaoping54532/article/details/62886506
  • 参考:应用 http://blog.csdn.net/xuehanlin/article/details/8011321
  • 参考: socket 说明 http://blog.csdn.net/sureyonder/article/details/5633647




你可能感兴趣的:(知识管理)