Вопрос

first question here and I hope that you can help me :)

The code (below) is some code that was written a while back which listens for incoming packets on an open socket. The code works well and manages to listen to all incoming messages, however the problem seems to be with this function below. It seems like this code is always being run, which is causing it to use large amounts of CPU power and large amounts of RAM. I am unable to show much more code as there is lots of it. Just wondering if there is a better way of knowing that a packet has arrived. Here is the code:

**

{
    if (socket.getInputStream() != null)
    {
        if (socket.getInputStream().available() > 0)
        {
            int i = socket.getInputStream().available();
            byte[] buffer = new byte[Global.c_iRxArraySize];
            socket.getInputStream().read(buffer);

            short[] converted = new short[Global.c_iRxArraySize];
            for (int j = 0; j < i; j++)
            {
                converted[j] = (short) (buffer[j] & 0xff);
            }
            Global.sNoTransmittionRecievedTimeout = 0;

            p_DebugreceivedMessageSize = FindPacketSize(converted);
            p_DebugreceivedMessageCount = p_DebugreceivedMessageCount + 1;
            p_DebugreceivedMessageData = GetPacketContents(converted);

            Date date = new Date();
            SimpleDateFormat p_DebugreceivedMessageTime = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
            DateReceivedData = p_DebugreceivedMessageTime.format(date);

            List<String> DataListReceived = new ArrayList<String>();
            DataListReceived.add(Arrays.toString(p_DebugreceivedMessageData));

            MobileRxProtocol(converted);
            Global.p_ReconnectionTimer = 0;
        }
    }
Это было полезно?

Решение

If Global.c_iRxArraySize is of fixed size you could try to reuse buffer and converted, also you could try to reuse SimpleDateFormat, no need to create and destroy this for every call and the DataListReceived could be reused and cleaned in the end of this process.

Declare all this variables outside this scope and reuse then, I think that is the first step at least.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top