Skip to content

Instantly share code, notes, and snippets.

@c12i
Last active August 2, 2021 22:15
Show Gist options
  • Save c12i/30a8119cc87a21e515df7ae5b8b5bed2 to your computer and use it in GitHub Desktop.
Save c12i/30a8119cc87a21e515df7ae5b8b5bed2 to your computer and use it in GitHub Desktop.

WebSockets

Another chat app ...

<!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>Chat</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-12">
<form id="message-form">
<div class="col-sm-10">
<input class="form-control" type="text" id="user-message"
placeholder="enter your message">
</div>
<div class="col-sm-2">
<input type="submit" class="btn btn-primary btn-block" value="send">
</div>
</form>
</div>
<ul id="messages">
<!-- messages here -->
</ul>
</div>
</div>
<style>
input {
width: 100%;
}
#message-form,
#messages {
margin-top: 1rem;
}
#messages li {
list-style: none;
}
</style>
<script src="./socket.io/socket.io.js"></script>
<script>
const socket = io('http://localhost:4231')
socket.on('server-message', (msg) => {
console.info(msg)
socket.emit('message-to-server', { data: 'Hi from the client' })
})
const messageForm = document.getElementById('message-form')
messageForm.addEventListener('submit', (event) => {
event.preventDefault()
const input = document.getElementById('user-message')
socket.emit('new-message', { text: input.value })
input.value = ''
})
socket.on('message-to-clients', ({ text }) => {
const listGroup = document.getElementById('messages')
const listItem = document.createElement('li')
listItem.textContent = text
listGroup.appendChild(listItem)
})
</script>
</body>
</html>
const express = require('express')
const socketio = require('socket.io')
const app = express()
app.use(express.static(__dirname + '/public'))
const expressServer = app.listen(4231, () => {
console.info('listening for connections...')
})
const io = socketio(expressServer)
io.on('connection', (socket, _req) => {
socket.emit('server-message', 'Hello from the server side')
socket.on('message-to-server', (data) => {
console.info(data)
})
socket.on('new-message', ({ text }) => {
io.emit('message-to-clients', { text })
})
})
{
"name": "chat",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"socket.io": "^4.1.3"
},
"devDependencies": {
"nodemon": "^2.0.12"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment