pR0Ps
pR0Ps

Reputation: 2792

Reading a newline character from a socket in Delphi

I'm working on a program in Delphi that has to conform to the ADC standard protocol. This protocol specifies that each line is terminated with a newline character (#10#13 OR sLineBreak). The problem is that the newline character doesn't seem to be surviving the trip from the server to the program. Reading the data from the socket seems to simply give it all as one massive line. I was thinking it was something to do with the way the program displayed debug messages (to a TMemo object), but a Pos(sLineBreak, Buf) always returns 0 (meaning it couldn't find the string).

My code:

procedure OnRead(Sender: TObject; Socket: TCustomWinSocket);
begin
  //read all the data from the socket
  while Socket.ReceiveLength > 0 do
    Buf := Buf + Socket.ReceiveText;

  //use only complete lines
  while Pos(sLineBreak, Buf) > 0 do begin
    //parsing stuff
  end;
end;

Also, the server doesn't have to send the commands in different steps, it can send them all at once with newlines in them, hence the need to read the entire socket in, then go through it as opposed to assuming one command per socket read.

Upvotes: 2

Views: 1031

Answers (2)

Rob Kennedy
Rob Kennedy

Reputation: 163277

The protocol specification says "a newline (codepoint 0x0a) ends each message." That's a single character. In Delphi syntax, it's #10 or #$a.

The usual value for sLineBreak on Windows is #13#10 — the carriage return comes first, then the newline. The sequence #10#13 is not a line break on any platform I'm aware of.

Everything displays as one line in your memo control because you're receiving only newline characters, without the carriage returns, and TMemo expects both characters to end a line. It's the same as if you'd loaded a Unix-style text file in Notepad.

Upvotes: 5

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84169

Hmm, the page you link seems to firmly state in the message syntax that new line is a single char:

eol ::= #x0a

while sLineBreak is two chars on Windows as you state.

Upvotes: 3

Related Questions