óCoffeeScript Cookbook

Basic Client

Problem

You want to access a service provided over the network.

Solution

Create a basic TCP client.

In Node.js

net = require 'net'

domain = 'localhost'
port = 9001

connection = net.createConnection port, domain

connection.on 'connect', () ->
	console.log "Opened connection to #{domain}:#{port}."

connection.on 'data', (data) ->
	console.log "Received: #{data}"
	connection.end()

Example Usage

Accessing the Basic Server:

$ coffee basic-client.coffee
Opened connection to localhost:9001
Received: Hello, World!

Discussion

The most important work takes place in the connection.on ‘data’ handler, where the client receives its response from the server and would most likely arrange for responses to it.

See also the Basic Server, Bi-Directional Client, and Bi-Directional Server recipes.

Exercises

  • Add support for choosing the target domain and port based on command-line arguments or from a configuration file.