@@ -10,37 +10,63 @@ const server = http.createServer();
1010server . on ( 'request' , common . mustNotCall ( ) ) ;
1111
1212server . on ( 'upgrade' , function ( req , socket , upgradeHead ) {
13+ // Read the body:
1314 let reqBody = '' ;
1415 req . on ( 'data' , common . mustCall ( ( str ) => { reqBody += str ; } ) ) ;
1516 req . on ( 'end' , common . mustCall ( ( ) => {
1617 assert . strictEqual ( reqBody , 'request body' ) ;
17- socket . end ( ) ;
1818 } ) ) ;
1919
2020 assert . strictEqual ( upgradeHead . toString ( ) , 'upgrade head' ) ;
21+
22+ // Confirm the upgrade:
23+ socket . write ( 'HTTP/1.1 101 Switching Protocols\r\n' +
24+ 'Upgrade: custom-protocol\r\n' +
25+ 'Connection: Upgrade\r\n' +
26+ '\r\n' ) ;
27+
28+ // Check we see the upgraded protocol data only (not the
29+ // request body):
30+ socket . on ( 'data' , common . mustCall ( ( d ) => {
31+ assert . strictEqual ( d . toString ( ) , 'post-upgrade message' ) ;
32+ socket . end ( ) ;
33+ } ) ) ;
2134} ) ;
2235
23- server . listen ( 0 , function ( ) {
36+ server . listen ( 0 , async function ( ) {
2437 const conn = net . createConnection ( this . address ( ) . port ) ;
2538 conn . setEncoding ( 'utf8' ) ;
2639
27- conn . on ( 'connect' , function ( ) {
28- conn . write (
29- 'POST / HTTP/1.1\r\n' +
30- 'Upgrade: WebSocket\r\n' +
31- 'Connection: Upgrade\r\n' +
32- 'Content-Length: 12\r\n' +
33- '\r\n' +
34- 'request body' +
35- 'upgrade head'
36- ) ;
37- } ) ;
38-
39- conn . on ( 'end' , function ( ) {
40- conn . end ( ) ;
41- } ) ;
42-
43- conn . on ( 'close' , function ( ) {
44- server . close ( ) ;
45- } ) ;
40+ await new Promise ( ( resolve ) => conn . on ( 'connect' , resolve ) ) ;
41+
42+ // Write request headers, leave the body pending:
43+ conn . write (
44+ 'POST / HTTP/1.1\r\n' +
45+ 'host: localhost\r\n' +
46+ 'Upgrade: custom-protocol\r\n' +
47+ 'Connection: Upgrade\r\n' +
48+ 'transfer-encoding: chunked\r\n' +
49+ '\r\n'
50+ ) ;
51+
52+ await new Promise ( ( resolve ) => setTimeout ( resolve , 10 ) ) ;
53+
54+ // Write the body and part of the initial upgrade data. Most clients
55+ // shouldn't send this until after 101 response, but we want to make
56+ // sure it works even if weird cases.
57+ conn . write (
58+ 'C\r\nrequest body\r\n' +
59+ '0\r\n\r\n' +
60+ 'upgrade head'
61+ ) ;
62+
63+ const response = await new Promise ( ( resolve ) => conn . once ( 'data' , resolve ) ) ;
64+ assert . ok ( response . startsWith ( 'HTTP/1.1 101 Switching Protocols\r\n' ) ) ;
65+
66+ conn . write ( 'post-upgrade message' ) ;
67+
68+ await new Promise ( ( resolve ) => conn . on ( 'end' , resolve ) ) ;
69+
70+ conn . end ( ) ;
71+ server . close ( ) ;
4672} ) ;
0 commit comments