Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript server


May 09, 2021 CoffeeScript


Table of contents


Server

Problem

You want to provide a server on the network.

Solution

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"
    socket.end()

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

Use the example

Basic Client is accessible:

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

Discuss

The function passes a new socket for each client's new connection @net.createServer. The basic server interacts simply with the guest, but the complex server connects the socket to a dedicated handler and returns to the task of waiting for the next user.

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

Practice

  • Add support for selected target domains and ports based on command line parameters or profiles.