|
| 1 | +--- |
| 2 | +layout: recipe |
| 3 | +title: Bi-Directional Client |
| 4 | +chapter: Networking |
| 5 | +--- |
| 6 | + |
| 7 | +h2. Problem |
| 8 | + |
| 9 | +You want to access a service that provides a persistent connection over the network. |
| 10 | + |
| 11 | + |
| 12 | +h2. Solution |
| 13 | + |
| 14 | +Create a bi-directional TCP client. |
| 15 | + |
| 16 | +h3. Node.js |
| 17 | + |
| 18 | +{% highlight coffeescript %} |
| 19 | +net = require 'net' |
| 20 | + |
| 21 | +domain = 'localhost' |
| 22 | +port = 9001 |
| 23 | + |
| 24 | +ping = (socket, delay) -> |
| 25 | + console.log "Pinging server" |
| 26 | + socket.write "Ping" |
| 27 | + nextPing = -> ping(socket, delay) |
| 28 | + setTimeout nextPing, delay |
| 29 | + |
| 30 | +connection = net.createConnection port, domain |
| 31 | + |
| 32 | +connection.on 'connect', () -> |
| 33 | + console.log "Opened connection to #{domain}:#{port}" |
| 34 | + ping connection, 2000 |
| 35 | + |
| 36 | +connection.on 'data', (data) -> |
| 37 | + console.log "Received: #{data}" |
| 38 | + |
| 39 | +connection.on 'end', (data) -> |
| 40 | + console.log "Connection closed" |
| 41 | + process.exit() |
| 42 | +{% endhighlight %} |
| 43 | + |
| 44 | +h3. Example Usage |
| 45 | + |
| 46 | +Accessing the <a href="/chapters/networking/bi-directional-server.html">Bi-Directional Server</a>: |
| 47 | + |
| 48 | +*$ coffee bi-directional-client.coffee* |
| 49 | +Opened connection to localhost:9001 |
| 50 | +Pinging server |
| 51 | +Received: You have 0 peers on this server |
| 52 | +Pinging server |
| 53 | +Received: You have 0 peers on this server |
| 54 | +Pinging server |
| 55 | +Received: You have 0 peers on this server |
| 56 | +[...] |
| 57 | +Connection closed |
| 58 | + |
| 59 | +h2. Discussion |
| 60 | + |
| 61 | +This particular example initiates contact with the server and starts the conversation in the _on 'connect'_ handler. The bulk of the work in a real client, however, will lie in the _on 'data'_ handler, which processes output from the server. |
| 62 | + |
| 63 | +See also the <a href="/chapters/networking/bi-directional-server.html">Bi-Directional Server</a>, the <a href="/chapters/networking/basic-client.html">Basic Client</a>, and the <a href="/chapters/networking/basic-server.html">Basic Server</a> recipes. |
| 64 | + |
| 65 | +h3. Exercises |
| 66 | +* Add support for choosing the target domain and port based on command-line arguments or from a configuration file. |
0 commit comments