Sample code connects to a public echo web socket server, send a message, receive a response, and disconnect.
JavaScript code provides functions for a web socket and for logging webassembly code.
The main program logic is written in C, which is then compiled into a wasm file.
The results can be seen in the js console.
Compilation:
emcc ws_test.c -o ws_test.html -O1 -s WASM = 1 -s ONLY_MY_CODE = 1 -s EXPORTED_FUNCTIONS = "['_ getBuffer', '_ wsOnMessage', '_wsOnOpen', '_test']"
The result of the ws_test.wasm file is tiny. (431 bytes)
, wasm s-:
wasm2wast ws_test.wasm -o ws_test.wast
ws_test.c
extern void wsConnect(char *address);
extern void wsSend(char *message);
extern void wsClose();
extern void print(char *message);
char buffer[100];
char *getBuffer(){ return buffer; }
void wsOnMessage(){
print("received message");
print(buffer);
wsClose();
print("connection closed");
}
void wsOnOpen(){
print("connected");
wsSend("Hello WebAssembly !");
}
void test(){
wsConnect("ws://echo.websocket.org");
print("connecting...");
}
ws_test.html
<script>
var webSocket;
const memory = new WebAssembly.Memory({ initial: 256, maximum: 256 });
const buffer = new Uint8Array(memory.buffer);
var exports;
function toJsStr(offset){
var s="";
for(;;){
var b = buffer[offset++];
if( b == 0 )
return s;
s += String.fromCharCode(b);
}
}
function toCStr(str){
var offset = exports._getBuffer();
for (var i = 0; i < str.length; ++i) {
buffer[offset++] = str.charCodeAt(i);
}
buffer[offset] = 0;
}
function print(offset){
console.log(toJsStr(offset));
}
function wsConnect(offset){
webSocket = new WebSocket(toJsStr(offset));
webSocket.onopen = function(){
console.log("Socket is open");
exports._wsOnOpen();
};
webSocket.onmessage = function (evt){
var msg = evt.data;
console.log("Message is received...");
toCStr(msg);
exports._wsOnMessage();
};
}
function wsClose(){
webSocket.close();
}
function wsSend(offset){
webSocket.send(toJsStr(offset));
}
fetch('ws_test.wasm').then(response =>
response.arrayBuffer()
).then(bytes => {
var imports = {};
imports.env = {};
imports.env.memory = memory;
imports.env.memoryBase = 0;
imports.env.table = new WebAssembly.Table({ initial: 0, maximum: 0, element: 'anyfunc' });
imports.env.tableBase = 0;
imports.env._print = print;
imports.env._wsConnect = wsConnect;
imports.env._wsSend = wsSend;
imports.env._wsClose = wsClose;
return WebAssembly.instantiate(bytes, imports);
}
).then(module => {
exports = module.instance.exports;
exports._test();
}
);
</script>
'ONLY_MY_CODE = 1', wasm ,
, .
, : printf, malloc/free, strcpy!
: strcpy, strcat, strlen... - .
, , malloc/free C.