-
webSocket 연결node.js 2020. 12. 2. 02:34
동적 페이지 제작을 위해 웹소켓을 사용하여 서버와 클라이언트를 양방향으로 연결한다. 최신 브라우저는 대부분 지원하므로 socket.io같은 범용모듈을 사용하지 않고 그냥 html5 표준으로 제작(구형 익스플로러는 과감히 포ㅋ기ㅋ)
클라이언트
// 웹소켓 연결, http 서버와 같은 포트를 공유(웹소켓은 http 방식이라서 어쩌구...) const ws= new WebSocket('ws://localhost:8080'); // 기본 명령어 ws.onopen= (evt)=>{ alert(evt) } // 연결 ws.onclose= (evt)=>{ alert(evt) } // 연결 종료 ws.onerror= (evt)=>{ alert(evt) } // 에러 ws.onmessage= (evt)=>{ alert(evt) } // 서버로부터 메세지를 받았을 때 ws.send('message'); // 서버에 메세지 보낼 때 // 웹소켓 메세지는 문자열로 전달되므로 객체를 받았을 때는 파싱 필요 // 'data' 프로퍼티가 서버에서 전달하는 메세지임 ws.onmessage= (evt)=>{ let message= JSON.parse(evt.data); alert(message); } // 서버에 객체를 보낼 때는 문자열로 변환하여 보냄 let obj= new Object(); ws.send(JSON.stringify(obj));
서버(./routes/webSocket.js)
// 웹소켓 미들웨어 불러오기 const wsModule = require('ws'); // mongoDB.js 파일에 DB연결, 스키마 등을 정의 // 웹소켓 명령에서도 DB검색결과 등을 사용하기 위함 const {User} = require('./mongoDB'); // http서버와 포트를 공유하므로 따로 지정하지 않아도 됨 const server = (_server)=>{ const wss = new wsModule.Server( {server:_server} ); // 연결시 실행되는 명령 wss.on('connection', (ws,req)=>{ // 클라이언트 ip를 콘솔에 표시 let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; console.log(ip+' connected'); // 클라이언트로부터 메세지를 받았을 때 ws.on('message', evt=>{ // 인자로 전달된 메세지가 객체일 경우 파싱 let msg= JSON.parse(evt); // 위에서 mongoDB.js 모듈을 불러왔으므로 클라이언트 요청에 따른 DB검색 가능 User.findOne( {email:msg.userEmail} ).exec().then(user=>{ // 객체를 문자열로 변환하여 클라이언트에게 보냄 if(user) ws.send(JSON.stringify( {userEmail:true} ) ); else ws.send(JSON.stringify( {userEmail:false} )) }) }); // 오류 발생했을 때 ws.on('error', error=>{ console.log(ip+' error on connection : '+error) }); // 접속이 종료되었을 때 ws.on('close', ()=>{ console.log(ip+' connection closed') }) }) } module.exports = server
서버(./bin/www)
const webSocket = require('../routes/webSocket'); webSocket(server);