Async networking apps

The QuickJS WasmEdge Runtime supports the WasmEdge networking socket extension so that the JavaScript programs can make HTTP connections to the Internet. This article will show you both HTTP Client and HTTP Server examples.

The networking API in WasmEdge is non-blocking and hence supports asynchronous I/O intensive applications. With this API, the JavaScript program can open multiple connections concurrently. It polls those connections, or registers async callback functions, to process data whenever data comes in, without waiting for any one connection to complete its data transfer. That allows the single-threaded application to handle multiple multiple concurrent requests.

A JavaScript networking client example

Below is an example of JavaScript running an async HTTP client. You could find the code in example_js/wasi_http_client.js. The code below shows how to make an async HTTP GET request.

  1. async function get_test() {
  2. try {
  3. let ss = await net.connect('152.136.235.225:80');
  4. let req = new http.WasiRequest();
  5. req.headers = { 'Host': '152.136.235.225' };
  6. req.uri = '/get?a=123';
  7. req.method = 'GET';
  8. ss.write(req.encode());
  9. print('wait get');
  10. await handle_response(ss);
  11. print('get end');
  12. } catch (e) {
  13. print('catch:', e);
  14. }
  15. }

The program can open multiple requests while waiting for the servers to respond. Once a server responds, the handle_response() function is called asynchronously to process the response and to print out the content.

  1. async function handle_response(s) {
  2. let buf = new http.Buffer();
  3. let resp = undefined;
  4. while (true) {
  5. buf.append(await s.read());
  6. if (resp == undefined) {
  7. resp = buf.parseResponse();
  8. }
  9. if (resp instanceof http.WasiResponse) {
  10. let resp_length = resp.bodyLength;
  11. if (typeof (resp_length) === "number") {
  12. if (buf.length >= resp.bodyLength) {
  13. print('resp.body');
  14. print(newStringFromUTF8(buf.buffer));
  15. break;
  16. }
  17. } else {
  18. throw new Error('no support');
  19. }
  20. }
  21. }
  22. }

To run the JavaScript in the WasmEdge runtime, you can do this on the CLI.

  1. cd example_js
  2. wasmedge --dir .:. ../target/wasm32-wasi/release/wasmedge_quickjs.wasm wasi_http_client.js

The results printed to the console are as follows.

  1. {
  2. "args": {
  3. "a": "123"
  4. },
  5. "data": "hello",
  6. "files": {},
  7. "form": {},
  8. "headers": {
  9. "Content-Length": "5",
  10. "Host": "152.136.235.225"
  11. },
  12. "json": null,
  13. "origin": "20.124.39.106",
  14. "url": "http://152.136.235.225/post?a=123"
  15. }

The demo app does two HTTP requests. One is GET and the other is POST. The app waits for the responses from those two requests asynchronously, and processes them as they come in. From the console log, you can see how the two request handlers are interweaved.

A JavaScript networking server example

Below is an example of JavaScript running a TCP server listening at port 8000. The incoming requests are handled asynchronously. You could find the code in example_js/wasi_net_echo.js.

  1. import * as net from 'wasi_net';
  2. async function handle_client(cs) {
  3. try {
  4. while (true) {
  5. let d = await cs.read();
  6. if (d == undefined || d.byteLength <= 0) {
  7. break;
  8. }
  9. let s = newStringFromUTF8(d);
  10. cs.write('echo:' + s);
  11. }
  12. } catch (e) {
  13. print(e);
  14. }
  15. }
  16. async function server_start() {
  17. print('listen 8000 ...');
  18. try {
  19. let s = new net.WasiTcpServer(8000);
  20. for (var i = 0; i < 100; i++) {
  21. let cs = await s.accept();
  22. handle_client(cs);
  23. }
  24. } catch (e) {
  25. print(e)
  26. }
  27. }
  28. server_start();

The server_start() function starts the server at port 8000. When a request comes in, it accepts immediately and calls the handle_client() function to process it asynchronously when the request data is received later. While the handle_client() is waiting for the data to arrive from the network, the app could accept another request concurrently.

To run the JavaScript in the WasmEdge runtime, you can do this on the CLI. Since it is a server, you should run it in the background.

  1. cd example_js
  2. nohup wasmedge --dir .:. ../target/wasm32-wasi/release/wasmedge_quickjs.wasm wasi_net_echo.js &

Then you can test the server by querying it over the network.

  1. $ curl -d "WasmEdge" -X POST http://localhost:8000
  2. echo:WasmEdge

The wasi_net package provides a flexible asynchronous networking stack for JavaScript applications in WasmEdge. We are wrap it in high-level APIs for more advanced use cases. In the next section, we will show you how to handle HTTP requests with ease. In the React SSR article, we will discuss how to create a React stream SSR server with the async networking API.

A JavaScript HTTP server example

If you already knew the server’s requests and responses are in the HTTP protocol, there are additional helper functions to help you handle these requests. You could find the code in example_js/wasi_http_echo.js.

  1. import * as http from 'wasi_http';
  2. import * as net from 'wasi_net';
  3. async function handle_client(cs, handler_req) {
  4. let buffer = new http.Buffer();
  5. while (true) {
  6. try {
  7. let d = await cs.read();
  8. if (d.byteLength <= 0) {
  9. return;
  10. }
  11. buffer.append(d);
  12. let req = buffer.parseRequest();
  13. if (req instanceof http.WasiRequest) {
  14. handler_req(cs, req);
  15. break;
  16. }
  17. } catch (e) {
  18. print(e);
  19. }
  20. }
  21. }
  22. function handler_req(cs, req) {
  23. print("version=", req.version);
  24. print("uri=", req.uri);
  25. print("method=", req.method);
  26. print("headers=", Object.keys(req.headers));
  27. print("body=", newStringFromUTF8(req.body));
  28. let resp = new http.WasiResponse();
  29. let body = 'echo:' + newStringFromUTF8(req.body);
  30. let r = resp.encode(body);
  31. cs.write(r);
  32. }
  33. async function server_start() {
  34. try {
  35. let s = new net.WasiTcpServer(8000);
  36. for (var i = 0; i < 100; i++) {
  37. let cs = await s.accept();
  38. try {
  39. handle_client(cs, handler_req);
  40. } catch (e) {
  41. print(e);
  42. }
  43. }
  44. } catch (e) {
  45. print(e);
  46. }
  47. }
  48. server_start();

The server_start() function starts the server at port 8000. When a request comes in, it accepts immediately and calls the handle_client() async function to process the request data when the data is received later. Once the request is validated as an HTTP request, the handler function in turn calls handle_req() to parse the fields in the HTTP request, compose a HTTP reponse, and then send the response back. While the program is waiting for the request data to arrive from the network, it can accept another request concurrently.

To run the JavaScript in the WasmEdge runtime, you can do this on the CLI. Since it is a server, you should run it in the background.

  1. cd example_js
  2. nohup wasmedge --dir .:. ../target/wasm32-wasi/release/wasmedge_quickjs.wasm wasi_http_echo.js &

Then you can test the server by querying it over the network.

  1. $ curl -d "WasmEdge" -X POST http://localhost:8000
  2. echo:WasmEdge

With async HTTP networking, developers can create I/O intensive applications, such as database-driven microservices, in JavaScript and run them safely and efficiently in WasmEdge.