// 필요한 객체를 선언합니다. var net = require('net'); // net.Socket event handlers function onSocketConnect() { console.log('onSocketConnect: connection established'); } function onSocketData(socket, buffer) { console.log('onSocketData: data received'); process.stdout.write(buffer); } // emitted when the other side of the socket sends a FIN packet function onSocketEnd() { console.log('onSocketEnd: a client sent a FIN packet.'); } function onSocketTimeOut() { console.log('onSocketTimeOut: called.'); } // when the write buffer becomes empty function onSocketDrain() { console.log('onSocketDrain: called.'); } function onSocketError(err) { console.log('onSocketError: called.'); } function onSocketClose(had_error) { console.log('onSocketClose: connection closed.'); if(had_error) { console.log('onSocketClose: some error happend :('); } else { console.log('onSocketClose: no error :)'); } process.exit(0); } function onStdinData(socket, data) { socket.write(data); console.log('onStdinData: data sent'); } //////////////////////////////////////////////////////////////////////////////// // Beginning // argument parsing if (process.argv.length != 4) { console.log('Usage: node echo_client.js '); process.exit(0); } var host = process.argv[2]; var port = process.argv[3]; // 소켓 생성 var options = {'port': port, 'host': host}; var socket = net.createConnection(options); // 핸들러 설정 socket.on('connect', onSocketConnect); socket.on('end', onSocketEnd); socket.on('timeout', onSocketTimeOut); socket.on('drain', onSocketDrain); socket.on('error', onSocketError); socket.on('close', onSocketClose); // socket에 효과적으로 접근하기 위해서는 이 방법이 효과적입니다. socket.on('data', function (buffer) { onSocketData(socket, buffer) }); // stdin 활성화 process.stdin.resume(); process.stdin.on('data', function(data){onStdinData(socket, data);});