Slide 17
Slide 17 text
Echo Server case (3c): Bun server/ Bun client
// bun_server.js
const PORT = 8000;
Bun.serve({
host: "localhost",
port: PORT,
websocket: {
open(ws) {
setTimeout(() => {
ws.send('connected!');
}, 10);
},
message(ws, message) {
console.log( 'received: %s' , message);
ws.send( 'Echoback:' + message);
const text = '' + message;
if (text === 'QUIT') {
process.exit( 0);}
},
fetch(req, server) {
if (server.upgrade(req)) return;
return new Response("HTTP response" );
},
});
// client.js
const PORT = 8000;
const URL = 'ws://127.0.0.1:' + PORT;
const Client = require('ws').WebSocket;
const ws = new Client(URL);
ws.on('open', function open() {
ws.send('Hello');
});
ws.on('message', function message(data) {
console.log('received: %s' , data);
const text = '' + data;
if (text === 'Echoback:Hello' ) {
console.log('got hello' );
ws.send('QUIT');
}
});
$ bun bun_server.js $ bun client.js
Tips2: for Ubuntu 22.04
NOT both, only one
OK
Tips1