óCoffeeScript Cookbook

Basic Server


You want to provide a service over a network.


Create a basic TCP server.

In Node.js

net = require 'net'

domain = 'localhost'
port = 9001

server = net.createServer (socket) ->
	console.log "Received connection from #{socket.remoteAddress}"
	socket.write "Hello, World!\n"

console.log "Listening to #{domain}:#{port}"
server.listen port, domain

Example Usage

Accessed by the Basic Client:

$ coffee basic-server.coffee
Listening to localhost:9001
Received connection from
Received connection from


The function passed to @net.createServer@ receives the new socket provided for each new connection to a client. This basic server simply socializes with its visitors but a hard-working server would pass this socket along to a dedicated handler and then return to the task of waiting for the next client.

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


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