@@ -21,10 +21,10 @@ function must(result) {
2121 return /** @type {T } */ ( result )
2222}
2323/**@param {os.FileDescriptor } fd */
24- function * recvLines ( fd ) {
24+ async function * recvLines ( fd ) {
2525 const chunk = new Uint8Array ( 1 ) ;
2626 let line = '' ;
27- while ( os . read ( fd , chunk . buffer , 0 , chunk . byteLength ) > 0 ) {
27+ while ( await os . recv ( fd , chunk . buffer ) > 0 ) {
2828 const char = String . fromCharCode ( ...chunk ) ;
2929 if ( char == '\n' ) {
3030 yield line ;
@@ -36,7 +36,7 @@ function* recvLines(fd) {
3636/** @param {os.FileDescriptor } fd @param {string[] } lines */
3737function sendLines ( fd , lines ) {
3838 const buf = Uint8Array . from ( lines . join ( '\r\n' ) , c => c . charCodeAt ( 0 ) ) ;
39- os . write ( fd , buf . buffer , 0 , buf . byteLength ) ;
39+ os . send ( fd , buf . buffer ) ;
4040}
4141//USAGE: qjs http_server.js [PORT=8080 [HOST=localhost]]
4242const [ port = "8080" , host = "localhost" ] = scriptArgs . slice ( 1 ) ;
@@ -47,19 +47,20 @@ const sock_srv = must(os.socket(os.AF_INET, os.SOCK_STREAM));
4747must ( os . setsockopt ( sock_srv , os . SO_REUSEADDR , new Uint32Array ( [ 1 ] ) . buffer ) ) ;
4848must ( os . bind ( sock_srv , ai [ 0 ] ) ) ;
4949must ( os . listen ( sock_srv ) ) ;
50-
51- console . log ( `Listening on http://${ ai [ 0 ] . addr } :${ ai [ 0 ] . port } ...` ) ;
52-
50+ //os.signal(os.SIGINT, ()=>os.close(sock_srv)); // don't work
51+ console . log ( `Listening on http://${ host } :${ port } (${ ai [ 0 ] . addr } :${ ai [ 0 ] . port } ) ...` ) ;
52+ const openCmd = { linux : "xdg-open" , darwin : "open" , win32 : "start" } [ os . platform ] ;
53+ if ( openCmd ) os . exec ( [ openCmd , `http://${ host } :${ port } ` ] ) ;
5354while ( true ) { // TODO: break on SIG*
54- const [ sock_cli ] = os . accept ( sock_srv ) ;
55+ const [ sock_cli ] = await os . accept ( sock_srv ) ;
5556
5657 const lines = recvLines ( sock_cli ) ;
57- const [ method , path , http_ver ] = ( lines . next ( ) . value || '' ) . split ( ' ' ) ;
58+ const [ method , path , http_ver ] = ( ( await lines . next ( ) ) . value || '' ) . split ( ' ' ) ;
5859 let safe_path = '.' + path . replaceAll ( / \. + / g, '.' ) ; // may += index.html later
5960 console . log ( method , safe_path , http_ver ) ;
6061
6162 const headers = new Map ( )
62- for ( const line of lines ) {
63+ for await ( const line of lines ) {
6364 const header = line . trimEnd ( ) ;
6465 if ( ! header ) break ;
6566 const sepIdx = header . indexOf ( ': ' ) ;
@@ -86,11 +87,9 @@ while (true) { // TODO: break on SIG*
8687 const fd = must ( os . open ( safe_path ) ) ;
8788 const fbuf = new Uint8Array ( 4096 ) ;
8889 for ( let got = 0 ; ( got = os . read ( fd , fbuf . buffer , 0 , fbuf . byteLength ) ) > 0 ; ) {
89- os . write ( sock_cli , fbuf . buffer , 0 , got ) ;
90+ os . send ( sock_cli , fbuf . buffer , got ) ;
9091 }
9192 }
9293
9394 os . close ( sock_cli ) ;
9495}
95-
96- os . close ( sock_srv ) ;
0 commit comments