读取InputStream字节

时间:2017-06-08 16:48:17

标签: java

我正在尝试获取inputStream clientSocket的字节。代码是用C ++编写的,我试图用Java编写。

我通过在Java中调用ClientSocket::receive方法获取getBytes()的字节数。这与ClientSocket::receive()方法中的相同吗? Java是否在C ++中包含recv之类的方法?

C ++代码:

//! Main function containing an endless loop which accepts and handels connections.
int _tmain(int argc, _TCHAR* argv[])
{
    while (true) {
        try {
            ServerSocket serverSocket;
            ClientSocket clientSocket(serverSocket.acceptConnection());
            try {
                SmartCard smartCard;
                handleConnection(clientSocket, smartCard);
            } catch (SmartCardException &e) {
                printf("SC Error: %s\n", e.what());
                SC_TCPPACKET answerMessage;
                answerMessage.type = e.getErrorCode();
                answerMessage.dLen = 0;
                clientSocket.send((char*)&answerMessage, answerMessage.dLen + MESSAGE_HEADER_LENGTH);
                throw e;
            }
        } catch (std::runtime_error &e) {
            printf("Error occured, resetting active connection.\nError message: %s\n", e.what());
        }
    }
    return 0;
}


//! Reads incoming stream and forwards complete pakets to the message handler defined above.
void handleConnection(ClientSocket &clientSocket, SmartCard &smartCard)
{
    BYTE receiveBuffer[RECEIVE_BUFFER_LENGTH];
    SC_TCPPACKET receivedMessage;
    DWORD bufferOffset = 0; // Number of unprocessed bytes overall
    int receivedBytes;      // Number of received bytes in current iteration
    do {
        receivedBytes = clientSocket.receive(((char*)receiveBuffer)+bufferOffset, RECEIVE_BUFFER_LENGTH-bufferOffset);
        bufferOffset += receivedBytes;
        while (bufferOffset >= MESSAGE_HEADER_LENGTH) { // header information with length available
            memcpy(&receivedMessage, receiveBuffer, MESSAGE_HEADER_LENGTH);
            if (receivedMessage.dLen > MESSAGE_MAXIMUM_LENGTH)
                throw std::runtime_error("Possible overflow attack, closing socket!");
            if (receivedMessage.dLen <= bufferOffset - MESSAGE_HEADER_LENGTH) { // paket complete
                // copy out whole package data
                memcpy(&receivedMessage, receiveBuffer, MESSAGE_HEADER_LENGTH + receivedMessage.dLen);
                // setting offset for remaining data in buffer
                bufferOffset -= MESSAGE_HEADER_LENGTH + receivedMessage.dLen;
                // move remaining data of buffer to front
                memmove(receiveBuffer, receiveBuffer + MESSAGE_HEADER_LENGTH + receivedMessage.dLen, bufferOffset);
                handleMessage(receivedMessage, clientSocket, smartCard);
            } else {
                break; // no further pakets to process, back to reading more data
            }
        }
    } while (receivedBytes > 0);
}


int ClientSocket::receive(char * buffer, int len, int flags)
{
    int ret = recv(socket, buffer, len, flags);
    if (ret == SOCKET_ERROR)
        throw ClientSocketException();

    printf("CS RX(%3d): ", ret);
    for (int b = 0; b < ret; ++b)
        printf("%02x ", (BYTE) (buffer[b]));
    printf("\n");

    return ret;
}

Java代码

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class Test {

    public static void main(String args[]) throws Exception {
        InputStream inputStream = null;
        ServerSocket serverSocket = new ServerSocket(27015);
        while (true) {
            Socket clientSocket = serverSocket.accept();
            inputStream = clientSocket.getInputStream();
            int byteData = Test.getBytes(inputStream, 512);
            System.out.println("Test");

        }
    }

    public static int getBytes(InputStream is, int size) throws IOException {
        int len;
        byte[] buf;

        if (is instanceof ByteArrayInputStream) {
            size = is.available();
            buf = new byte[size];
            len = is.read(buf, 0, size);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            buf = new byte[size];
            while ((len = is.read(buf, 0, size)) != -1) {
                bos.write(buf, 0, len);
            }
            buf = bos.toByteArray();
        }
        return buf.length;
    }

}

1 个答案:

答案 0 :(得分:1)

  

Java是否在C ++中包含recv之类的方法?

是的,你已经打电话了。

它是int read(byte[] b, int off, int len)方法,它从流/套接字读取到给定长度的给定缓冲区,并返回读取的实际字节数。

ssize_t recv(int sockfd, void *buf, size_t len, int flags)完全相同。

至于您的getBytes()方法。

该方法的目的是什么,它消耗流中的字节,丢弃它们

C代码中没有任何内容接近该方法正在做的事情。

摆脱它!!!