File: socket.sml

package info (click to toggle)
mlton 20130715-3
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 60,900 kB
  • ctags: 69,386
  • sloc: xml: 34,418; ansic: 17,399; lisp: 2,879; makefile: 1,605; sh: 1,254; pascal: 256; python: 143; asm: 97
file content (50 lines) | stat: -rw-r--r-- 1,625 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
val addr = INetSock.any 0
val socket = INetSock.TCP.socket ()
val _ = Socket.bind (socket, addr)
val _ = Socket.listen (socket, 5)
val addr = Socket.Ctl.getSockName socket

fun read socket : string =
   Byte.unpackStringVec (Word8VectorSlice.full (Socket.recvVec (socket, 100)))

fun readNB socket : string option =
   Option.map (Byte.unpackStringVec o Word8VectorSlice.full)
   (Socket.recvVecNB (socket, 100))
   
fun write (socket, s: string): unit =
   (Socket.sendVec (socket, Word8VectorSlice.full (Byte.stringToBytes s))
    ; ())

val _ =
   print (case Socket.acceptNB socket of
             NONE => "OK\n"
           | SOME _ => "WRONG\n")

val _ =
   case Posix.Process.fork () of
      NONE =>
         let
            val _ = Posix.Process.sleep (Time.fromSeconds 1)
            val (socket, _) = Socket.accept socket
            val _ = print (read socket)
            val _ = print (case readNB socket of
                              NONE => "NONE\n"
                            | SOME s => s)
            val _ = write (socket, "goodbye, world\n");
            val _ = Socket.close socket
         in
            ()
         end
    | SOME pid => 
         let
            val socket' = INetSock.TCP.socket ()
            val _ = Socket.connect (socket', addr)
            val _ = write (socket', "hello, world\n")
            val _ = print (read socket')
            val _ = Socket.close socket'
            val (pid', status)  = Posix.Process.wait ()
         in
            if pid = pid' andalso status = Posix.Process.W_EXITED
               then ()
            else print "child failed\n"
         end