Skip to content

Commit 28c7d6b

Browse files
committed
README++
1 parent c743e36 commit 28c7d6b

1 file changed

Lines changed: 43 additions & 2 deletions

File tree

README.md

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ direct TCP connection to the endpoint server.
1111

1212
Since this agent implements the CONNECT HTTP method, it also works with other
1313
protocols that use this method when connecting over proxies (i.e. WebSockets).
14+
See the "Examples" section below for more.
1415

1516

1617
Installation
@@ -23,8 +24,10 @@ $ npm install https-proxy-agent
2324
```
2425

2526

26-
Example
27-
-------
27+
Examples
28+
--------
29+
30+
#### `https` module example
2831

2932
``` js
3033
var url = require('url');
@@ -50,6 +53,44 @@ https.get(opts, function (res) {
5053
});
5154
```
5255

56+
#### `ws` WebSocket connection example
57+
58+
``` js
59+
var url = require('url');
60+
var WebSocket = require('ws');
61+
var HttpsProxyAgent = require('https-proxy-agent');
62+
63+
// HTTP/HTTPS proxy to connect to
64+
var proxy = process.env.http_proxy || 'http://168.63.76.32:3128';
65+
console.log('using proxy server %j', proxy);
66+
67+
// WebSocket endpoint for the proxy to connect to
68+
var endpoint = process.argv[2] || 'ws://echo.websocket.org';
69+
var parsed = url.parse(endpoint);
70+
console.log('attempting to connect to WebSocket %j', endpoint);
71+
72+
// create an instance of the `HttpsProxyAgent` class with the proxy server information
73+
var opts = url.parse(proxy);
74+
75+
// IMPORTANT! Set the `secureEndpoint` property to `false` when connecting
76+
// over "ws://", but `true` when connecting over "wss://"
77+
opts.secureEndpoint = parsed.protocol && parsed.protocol == 'wss:';
78+
79+
var agent = new HttpsProxyAgent(opts);
80+
81+
// finally, initiate the WebSocket connection
82+
var socket = new WebSocket(endpoint, { agent: agent });
83+
84+
socket.on('open', function () {
85+
console.log('"open" event!');
86+
socket.send('hello world');
87+
});
88+
89+
socket.on('message', function (data, flags) {
90+
console.log('"message" event! %j %j', data, flags);
91+
socket.close();
92+
});
93+
```
5394

5495
License
5596
-------

0 commit comments

Comments
 (0)