Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

Contents

Hello World HTTP 서버

간단 버전

var http = require('http');

http.createServer(function (request, response) {
	response.writeHead(200, {'Content-Type': 'text/plain'});
	response.end("Hello world\n")
}).listen(8000, '0.0.0.0');

console.log('Server started')

실행 및 테스트
# nodejs helloworld.js
# curl localhost:8000 

모듈화 버전

# cat hello.js
var http = require('http');

function start() {
	function onRequest(request, response) {
		response.writeHead(200, {'Content-Type': 'text/plain'});
		response.write("Hello World!!");
		response.end();
	}
	http.createServer(onRequest).listen(5555);
	console.log("Server has started.");
}

exports.run = start;

# cat app.js
var app = require('./hello.js')
app.run()
  • exports 객체와 모듈

Echo 서버

var net=require('net')

net.createServer(function(socket) {
	socket.write("Echo Server....\n")
	socket.on('data', function(data) {
		socket.write(data.toString())
	})
}).listen(8000, 'localhost')

테스트
# nc localhost 8000
Echo Server....
Hello World
Hello World
Ok
Ok

Chat 서버

Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

var net=require('net');
var sockets = []

net.createServer(function(socket) {
	sockets.push(socket);
	socket.write("Hello !!\n");
	socket.on('data', function(data) {
		var i;
		for (i = 0; i < sockets.length; i++) {
			if (sockets[i] === socket ) continue;
			sockets[i].write(data.toString());
		}
	});
	socket.on('end', function() {
		var i = sockets.indexOf(socket);
		sockets.remove(i);
	});
}).listen(1234)
  • 객체와 메서드