닷넷의 SerialPort 클래스를 이용해 통신을 하다보니 문제가 발생하였다.

 

Read 메서드를 이용해 특정 바이트 수만큼 읽는 로직을 작성하였는데,

 

예를들어 4바이트를 Read하면 4바이트 이하여도 Read 메서드의 Blocking이 풀리는 현상이다.

 

사실 버그는 아니고......msdn을 살펴보니 수신 버퍼가 비어있지 않다면 해당  Read 메서드의 인자인  count 이하만큼

 

읽어버리는 것을 알았다.

 

아래와 같이 처리해주면 count만큼 수신할 수 있다.

 

/// <summary>

/// 데이터를 수신한다.

/// </summary>

/// <param name="buf">수신할 버퍼</param>

/// <param name="offset">데이터를 저장할 위치</param>

/// <param name="count">데이터 저장 바이트 수</param>

/// <returns></returns>

public int Receive(byte[] buf, int offset, int count)

{

    if (this.serialPort != null)

    {

        int bytesExpected = count, bytesRead = 0;

        while (bytesExpected > 0 && (bytesRead = serialPort.Read(buf, offset, bytesExpected)) > 0)

        {

            offset += bytesRead;

            bytesExpected -= bytesRead;

        }

        return count;

    }

    else

        return 0;

} 

 

+ Recent posts