# /etc/apache2/sites-available/000-default.conf 내용 추가
<VirtualHost *:80>
ServerName example.com
ProxyRequests Off
ProxyPreserveHost On
ProxyVia Full
<Proxy *>
Require all granted
</Proxy>
<Location /nodejs>
ProxyPass http://localhost:3000
ProxyPassReverse http://localhost:3000
</Location>
<Directory "/var/www/example.com/html">
AllowOverride All
</Directory>
</VirtualHost>
3000포트로 허용함을 설정
$ sudo service apache2 restart
아파치 서버 재구동
# /var/www/html/nodejs/hello.js
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World! Node.js is working correctly.\n');
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
console.log('It is running now...');
마찬가지로 3000포트 연결 설정
hello.js 파일 실행
$ node /var/www/html/nodejs/hello.js
console.log 했던 내용 출력
http://example.com:8080/node.js/ 접속
접속완료
일단 서버 내에서 8080포트로 접속하여 3000포트의 Websocket communication 로그 출력이 완료되었다.
Node.js, JavaScript의 Websocket을 이용해 간단한 셀프 채팅 어플리케이션을 구현하겠습니다.
웹소켓의 기본적인 구성은 다음과 같습니다.
2단계로 구성한 웹소켓
굳이 개념치 않다면 안보셔도 무방합니다.
■ ws 설치
$ npm install ws
우선 npm 명령어로 ws (web socket) 을 설치하도록 하겠습니다.
■ Server.js
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer( { port: 8900 } ); // 포트번호는 자유롭게 작성해주세요.
wss.on( 'connection', function(ws){
console.log("connected");
// 클라이언트가 메시지를 전송했을 때 수신하여 다시 보내는 과정.
ws.on( 'message', function(msg){
console.log("msg[" + msg + "]" );
ws.send( msg );
});
});
포트번호(port)는 본인이 사용하는 포트번호를 지정하면 됩니다.
그리고 구동하는 방법은 터미널에서
$ node server.js
로 js파일을 구동시킵니다.
■ Client.html
html파일이던 php파일이던 상관없습니다. 중요한건 javascript로 한다는 것이니까요.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<title>Document</title>
</head>
<body>
<form>
<input id="Send" type="text" autofocus> <!--메시지 작성 영역-->
<button type="button" onclick="sendMessage();" >Send</button> <!--전송버튼-->
</form>
<div id="Recv"></div> <!-- 보낸 메시지가 기록되는 곳 -->
<script>
$( document ).ready( function() {
var txtRecv = $('#Recv');
ws = new WebSocket("ws://localhost:8900");
// websocket 서버에 연결되면 연결 메시지를 화면에 출력한다.
ws.onopen = function(e){
txtRecv.append( "connected<br>" );
};
// websocket 에서 수신한 메시지를 화면에 출력한다.
ws.onmessage = function(e){
txtRecv.append( e.data + "<br>" );
};
// websocket 세션이 종료되면 화면에 출력한다.
ws.onclose = function(e){
txtRecv.append( "closed<br>" );
}
});
// 사용자가 입력한 메시지를 서버로 전송한다.
function sendMessage() {
var txtSend = $('#Send');
ws.send( txtSend.val() );
txtSend.val( "" );
txtSend.focus()
}
</script>
</body>
</html>
■ 결과
· 서버 구동 -> 연결 -> 페이지 접속마다 터미널에 "connected" 라는 로그가 찍힙니다.
· 메시지를 작성하고 버튼을 통해 전송하였을 때,
■ 결론
-> 몇가지 보완할 내용이 존재하긴 하다.
1. jQuery로 작성하였다는 점. -> 필자는 jQuery를 선호하지 않는다. 비동기통신 위주로 사용하는 스타일인데, 예전에는 ajax 사용할 때 사용했지만, 요즘은 axios 위주로 사용하기 때문에 이마저도 잘 사용하지 않는다.
2. 사소한 버그가 있다. -> 메시지를 작성하고 송출하였을 때, 해당 메시지가 웹페이지에 제대로 출력이 되지 않고, [ Object Object ] [ Blob ] 이런식으로 작성되더라. -> e.data를 통해 해당 내용을 append 시켜 작성하였는데, 아무래도 해당 node 자체가 입력이 된것이라 판단하다. -> 해결방법으로 <p> 를 하나 생성해서 해당 내용을 생성하여 삽입할 수 있다.
Javascript로 select box 내의 option들을 특정 조건에 의해 함수를 호출하여 제거하려고 한다. 검색 기능으로 사용하면 유용하다.
물론 select box 말고도 p, span, div...등등 부모-자식 관계의 태그들이라면 모두 가능하다.
Node . removeChild 를 사용한다.
const item_name = document.querySelector('#item_name') // item_name이라는 부모 요소
while (item_name.firstChild) { // 첫번째 자식 태그가 존재하면 무한 반복
item_name.removeChild(item_name.firstChild); // 첫번째 자식 태그를 제거한다.
}
sudo apt install nodejs
sudo apt install npm
// cache 제거. 안해주시면 에러 발생가능성이 있습니다.
sudo npm cache clean -f
// 전역에서 사용가능하게 npm을 n이라는 이름으로 다운로드
sudo npm install -g n
// 안정화 버전을 설치
sudo n stable
3. 확인
node -v
v16.13.0
npm -v
8.1.0
자꾸 오류 나고 그래서 삭제만 8번 넘게 진행한 것 같네요.
억울하고 분통터져
원래 뭘 진행하려고 했는지도 머리속에서 증발하게 되었습니다. ㅎㅎ 다시 무엇을 하려고했는지 떠나요~