Network Programming
Cangjie supports transport-layer TCP and UDP programming, as well as application-layer HTTP programming. TCP implements reliable connection-oriented communication through TcpSocket and TcpServerSocket, while UDP implements connectionless datagram transmission through UdpSocket. HTTP programming uses ClientBuilder and ServerBuilder from the stdx.net.http package.
Network I/O in Cangjie is blocking—calls to read, accept, and other methods will wait until data is ready. However, it's Cangjie lightweight threads that are blocked, not system threads. A blocked Cangjie thread will yield the system thread to other ready Cangjie threads. This design lets you write efficient concurrent network programs using a synchronous coding style.
A TCP server needs to first bind() to an address, then call accept() to wait for client connections. A TCP client calls connect() to connect to the server. Once connected, both parties can send and receive data through read() and write(). The example on the right demonstrates the basic TCP communication flow.
stdx.net.http package and require adding the stdx dependency in cjpm.toml. Socket APIs are in the std.net package and are part of the standard library.Running this code will start a TCP server and a client. Observe how data sent by the client is received and printed by the server.
The example binds port 0 first so the system allocates an available port, then uses that port for the client. No fixed port or startup delay is required. TCP is a byte stream: a single read() does not guarantee a complete message; real protocols must handle framing and partial reads.