socket.io
app.js (서버)
const express = require("express");
const app = express();
const path = require("path");
const http = require("http");
const server = http.createServer(app);
const socketIO = require("socket.io");
const io = socketIO(server);
app.use(express.static(path.join(__dirname, "src")));
const PORT = process.env.PORT || 5000;
io.on("connection", (socket) => {
console.log("연결 완료");
socket.on("chatting", (data) => {
console.log("data확인", data);
io.emit("chatting", data);
});
});
server.listen(PORT, () => console.log(`sever is running ${PORT}`));
index.html
<!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">
<title>Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="user-container">
대화명 : <input type="text" id="nickname">
</div>
<div class="display-container" id="scroller">
<ul class="chatting-list" id="anchor"></ul>
</div>
<div class="input-container">
<input type="text" class="chatting-input">
<button class="send-button">보내기</button>
</div>
<script src="/socket.io/socket.io.js"> </script>
<script src="js/chat.js"></script>
</html>
chat.js (클라이언트)
"use strict";
const socket = io();
console.log("소켓확인", socket);
const nickname = document.querySelector("#nickname");
const chatList = document.querySelector(".chatting-list");
const chatInput = document.querySelector(".chatting-input");
const sendButton = document.querySelector(".send-button");
sendButton.addEventListener("click", () => {
const param = {
name: nickname.value,
msg: chatInput.value,
};
socket.emit("chatting", param);
});
socket.on("chatting", (data) => {
const li = document.createElement("li");
li.innerText = `${data.name}님이 - ${data.msg}`;
chatList.appendChild(li);
const huh = document.getElementById("scroller");
console.log("허쩜 스크롤항이트", huh.scrollHeight);
huh.scrollTop = huh.scrollHeight;
});