Reputation: 14063
I'm trying to write a minimal TCP server in Standard ML and getting some type errors I don't understand. What I've got so far is
fun sendHello sock =
let val res = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello world!\r\n\r\n"
val wds = map (fn c => Word8.fromInt (Char.ord c)) (String.explode res)
val slc = ArraySlice.full (Array.fromList wds)
in
Socket.sendArr (sock, slc)
Socket.close sock
end
fun acceptLoop serv =
let val (s, _) = Socket.accept serv
in print "Accepted a connection...\n";
sendHello s;
acceptLoop serv
end
fun serve () =
let val s = INetSock.TCP.socket()
in Socket.Ctl.setREUSEADDR (s, true);
Socket.bind(s, INetSock.any 8989);
Socket.listen(s, 5);
print "Entering accept loop...\n";
acceptLoop s
end
The latter two functions work fine (if I comment out the sendHello
line, they typecheck without complaint, and set up a server that prints Accepted a connection...
every time a client connects).
From what I understand from the Socket struct
, sendArr
should take a tuple of socket and a Word8ArraySlice.slice
, which I'm reasonably sure I'm providing.
SMLNJ
- ArraySlice.full (Array.fromList (map (fn c => Word8.fromInt (Char.ord c)) (String.explode "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello world!\r\n\r\n"))) ;;
val it =
SL
{base=[|0wx48,0wx54,0wx54,0wx50,0wx2F,0wx31,0wx2E,0wx31,0wx20,0wx32,0wx30,
0wx30,...|],start=0,stop=49} : Word8.word ArraySlice.slice
-
The error I get is
- fun sendHello sock =
let val res = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello world!\r\n\r\n"
val wds = map (fn c => Word8.fromInt (Char.ord c)) (String.explode res)
val slc = ArraySlice.full (Array.fromList wds)
in
Socket.sendArr (sock, slc)
Socket.close sock
end ;;
= = = = = = = stdIn:35.8-36.25 Error: operator and operand don't agree [tycon mismatch]
operator domain: ('Z,Socket.active Socket.stream) Socket.sock *
?.Word8ArraySlice.slice
operand: ('Z,Socket.active Socket.stream) Socket.sock *
Word8.word ArraySlice.slice
in expression:
Socket.sendArr (sock,slc)
-
Can anyone educate me regarding what I need to do to get this working?
Upvotes: 2
Views: 423
Reputation: 14063
It turns out that an ArraySlice
of Word8
s is not the same thing as a Word8ArraySlice
. In order to get the latter from a string, you need to call packString
with an appropriate array. I decided to use Vector
s instead, which meant that I could do Word8VectorSlice.full (Byte.stringToBytes res)
to get a thing I could then send out via Socket.sendVec
. The below works fine:
fun sendHello sock =
let val res = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello world!\r\n\r\n"
val slc = Word8VectorSlice.full (Byte.stringToBytes res)
in
Socket.sendVec (sock, slc);
Socket.close sock
end
Upvotes: 3