Socket
Socket is a TCP connection with the same calls on macOS, iOS, Android, Linux
and Windows. From 0.72.
#import "Socket.xc" // not in the Foundation umbrella: import it by nameOverview
Section titled “Overview”try { Socket* s = Socket.connect(String.withCString("localhost"), (u16)7070); s.writeString(String.withCString("hello\n")); s.waitReadable((i32)1000); // up to a second for a reply Data* reply = s.readAvailable((u32)4096); s.close(); }catch (SocketError e) { Stdio.printf("%s\n", e.message().cString()); // cannot connect to localhost:7070 }It hides what differs between the hosts: Winsock’s start-up, SOCKET and
closesocket on Windows, the two addrinfo layouts, and SIGPIPE from a peer
that went away. The address comes from getaddrinfo, IPv4 or IPv6.
Reading never blocks. read and readAvailable
return what has arrived, so a client can poll from a timer and the
run loop keeps turning; waitReadable
blocks for as long as the caller chooses. A connection that fails, or that the
peer closes, is closed here, and reads then report it.
Http speaks HTTP over the same declarations.
Topics
Section titled “Topics”Connecting · connect · isOpen · close
Writing · write · writeData · writeString
Reading · waitReadable · read · readAvailable
Errors · SocketError
Connecting
Section titled “Connecting”connect
Section titled “connect”static Socket* connect(String* host, u16 port) throwsA connection to host:port (a name or a numeric address, IPv4 or IPv6),
blocking until it is made or refused. Throws a SocketError
saying why when it cannot be.
isOpen
Section titled “isOpen”bool isOpen(void)void close(void)A socket is also closed when it is freed.
Writing
Section titled “Writing”bool write(u8* p, u32 n)Sends every byte; false when the connection has gone (it is then closed).
writeData
Section titled “writeData”bool writeData(Data* d)writeString
Section titled “writeString”bool writeString(String* s)The String’s UTF-8 bytes, without a terminator.
Reading
Section titled “Reading”waitReadable
Section titled “waitReadable”bool waitReadable(i32 ms)Waits up to ms milliseconds (0: not at all, -1: for as long as it takes) for
something to read, or for the peer to go; true when read would return
something other than 0.
i32 read(u8* p, u32 cap)What has arrived, without waiting: the number of bytes (up to cap), 0 when
nothing has yet, -1 when the peer has closed the connection or it failed (it is
then closed).
readAvailable
Section titled “readAvailable”Data* readAvailable(u32 max)The same as Data: empty when nothing has arrived, null
when the connection is closed.
Errors
Section titled “Errors”SocketError
Section titled “SocketError”class SocketError <Error>String* message(void)What connect throws: cannot resolve the host '…',
cannot connect to host:port, or no TCP sockets on this platform.