Dom
Dom

Reputation: 153

Ocaml comparison not working

I am trying to write a simple server program in Ocaml that communicates with other processes via a socket. I currently have a problem that the strings the server reads (with input_line ic) do not seem to compare with other strings properly. For example, I run the server program and use telnet to connect to it, if I send "end" as a line, the server program trys to match with "end", but this doesn't work as expected. The function that handles communication is service (below), which is called to handle a client as part of a forking server (something like the double fork treatment here).

let service ic oc
    try while true do
        let instr = input_line ic in
        match instr with
        | "end" -> print_endline "matching end" (* this never runs *)
        | _ -> output_string oc ((String.uppercase instr) ^ "\n") ; flush oc
    done
    with End_of_file -> print_endline "Input stream ended."
;;

In fact, if I do print_endline (string_of_bool ("end" = instr)) I always get false (even when I send "end" via telnet). To try and get some sense of what is going I printed out the result of different comparison operations between the let-binding and the try block:

print_endline instr ;
print_endline "end" ;
print_endline (string_of_bool ("end" = instr)) ;
print_endline (string_of_bool ("end" == instr)) ;
print_endline (string_of_int (String.compare "end" instr)) ;

When I send "end" the server now prints out

end

end

false

false

-1

I'm really lost as to what could be going on - I presume it must be something about getting the instr via reading from a socket, as usually you can compare strings just fine.

I don't think I actually had a question in all that background so here are a few variants that could work:

Upvotes: 1

Views: 147

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66803

My guess is that there are carriage returns in the strings coming in from telnet. As I recall, the old protocols tend to send CRLF at the ends of lines.

You might try printing the string out using String.escaped.

It's pretty unlikely you're seeing a bug in OCaml.

Upvotes: 2

Related Questions