
강의 #3
전체 클라이언트 제어
- 한 서버에 여러 클라이언트들이 연결이 됨
- 모든 클라이언트들을 제어할 수 있어야 함
- 배열로 각 유저들에 대한 websocket과 user_id(각 유저를 구별할 수 있는 식별값)를 저장
JSON.stringify
- 배열 또는 오브젝트 형식의 변수를 문자열로 바꿔준다.
서버 전체 코드
const WebSocket = require("ws");
const ws = new WebSocket.Server({ port:8008 });
let user_id = 0;
let ALL_WS = [];
ws.on("connection", function connect(websocket, req) {
user_id++;
console.log("NEW USER CONNECT ("+user_id+")");
ALL_WS.push({"ws":websocket, "user_id":user_id});
sendUserId(user_id);
function sendUserId(user_id) {
let data = {"code":"my_user_id", "msg":user_id};
websocket.send(JSON.stringify(data));
}
});
