Example: Use Socket Api in WAMR

The related code/working directory of this example resides in directory {WAMR_DIR}/samples/socket-api

This sample demonstrates how to use WAMR socket-api to develop wasm network applications. Two wasm applications are provided: tcp-server and tcp-client, and this sample demonstrates how they communicate with each other.

Preparation

Please install WASI SDK, download the wasi-sdk release and extract the archive to default path /opt/wasi-sdk. And install wabt, download the wabt release and extract the archive to default path /opt/wabt

Build the sample

mkdir build
cd build
cmake ..
make

iwasm and the following Wasm modules (along with their corresponding native version) will be generated:

  • addr_resolve.wasm, addr_resolve

  • send_recv.wasm, send_recv

  • socket_opts.wasm, socket_opts

  • tcp_client.wasm, tcp_client

  • tcp_server.wasm, tcp_server

  • udp_client.wasm, udp_client

  • udp_server.wasm, udp_server

Note that iwasm is built with libc-wasi and lib-pthread enabled.

Run workload

TCP client/server

Start the tcp server, which opens port 1234 and waits for clients to connect.

Start the tcp client, which connects the server and receives message.

The output of client is like:

send_recv.wasm contains a thread as a server and a thread as a client. They send and receive data via 127.0.0.1:1234.

The output is:

Socket options

socket_opts.wasm shows an example of getting and setting various supported socket options

The output is:

The timeout_client.wasm and timeout_server.wasm examples demonstrate socket send and receive timeouts using the socket options. Start the server, then start the client.

The output is:

The output is:

The multicast_client and multicast_server examples demonstrate receiving multicast packets in WASM. Start the client and then the server with a multicast IP address and port.

The output should be

The output should be

Domain name server resolution

addr_resolve.wasm demonstrates the usage of resolving a domain name

The command displays the host name and its corresponding IP address:

UDP client/server

Start the UDP server, which opens port 1234 and waits for clients to send a message.

Start the tcp client, which sends a message to the server and waits for the response.

The output of client is like:

The output of the server is like:

Documentation

Refer to socket api document for more details.

Last updated