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




  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值