Welcome to Gaming Nation!
This is gaming nation - the number 1 gaming news site in the world!
Check out Neocities!
chat-app/
├── public/
│ ├── index.html
│ ├── style.css
│ └── script.js
├── server.js
├── package.json
// server.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
server.listen(3000, () => {
console.log('Listening on http://localhost:3000');
});
Chat App
/*public/style.css*/
body {font:14px sans-serif;background:#f2f2f2;}
form {background:#fff;padding:10px;position:fixed;bottom:0;width:100%;display:flex;}
form input {flex:1; padding:10px;}
form button {padding: 10px;}
ul {list-style: none; padding:20px; margin-bottom: 60px;}
li {padding: 5px 10px; background: #fff; margin-bottom: 10px; border-radius: 4px;}
// public/script.js
const socket = io();
const form = document.getElementById('form');
const input = document.getElementById('input');
const messages = document.getElementById('messages');
form.addEventListener('submit', function (e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function (msg) {
const item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});