Skip to content

Instantly share code, notes, and snippets.

@pnakibar
Created October 6, 2016 21:36
Show Gist options
  • Save pnakibar/085d46131f047ebcc4fd556af6f191d4 to your computer and use it in GitHub Desktop.
Save pnakibar/085d46131f047ebcc4fd556af6f191d4 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Websocket tutorial</title>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
</head>
<body>
<h1>
Ultimate Web Chat 0.1.0
</h1>
<input id="name" type="text" placeholder="name">
<input id="password" type="password" placeholder="password">
<button id="login-button" name="button" onclick="login()">Login</button>
<button id="signup-button" name="button" onclick="signup()">Signup</button>
<div id='motd'></div>
<p id='messages'>
</p>
<input id="new-message" type="text" placeholder="New Message">
<button name="button" onclick="sendMessage()">Send</button>
<script>
const sioServerURL = 'http://localhost:3000';
// pegar o conteúdo dos inputs
function getNamePassword() {
const name = document.getElementById('name').value;
const password = document.getElementById('password').value;
return {
name,
password
}
}
const headers = new Headers();
headers.set('Content-Type', 'application/json');
// fazer o signup
function signup() {
return fetch(`${sioServerURL}/signup`, {
headers,
method: 'post',
body: JSON.stringify(getNamePassword()),
})
.then(x => x.json())
.then(token => loginWS(token));
}
// fazer o login
function login() {
var data = new FormData();
data.append('json', JSON.stringify(getNamePassword()));
console.log(data);
return fetch(`${sioServerURL}/login`, {
headers,
method: 'post',
body: JSON.stringify(getNamePassword()),
})
.then(x => x.json())
.then(token => loginWS(token));
}
// função que é chamada para enviarmos a mensagem
// hack simples para podermos ter acesso dentro do escopo global a uma função que vai ser definida dentro do outro escopo, mas evite utilizar esse tipo de 'recurso'
let sendMessage;
// irá realizar o login
function loginWS(token) {
const sioOptions = {
'query': 'token=' + token
};
const socket = io(sioServerURL, sioOptions);
const messages = document.getElementById('messages');
const motd = document.getElementById('motd');
socket.on('connect', () => {
socket.on('error', (data) => {
if (data.type === 'UnauthorizedError') {
motd.textContent = 'Suas credenciais estão inválidas!'
}
});
function addMessage({
userName,
message
}) {
const newDiv = document.createElement('div');
const newContent = document.createTextNode(`${userName}: ${message}`); // atualizada para novo modelo de mensagem
newDiv.appendChild(newContent);
messages.appendChild(newDiv);
}
function emitMessage() {
console.log('emit');
const newMessage = document.getElementById('new-message').value;
socket.emit('sent message', newMessage);
document.getElementById('new-message').value = "";
}
sendMessage = emitMessage; // hack
socket.on('hello', (data) => {
document.getElementById('motd').textContent = data;
})
socket.on('messages', (data) => {
data.forEach(m => addMessage(m));
})
socket.on('new message', (data) => {
console.log('new message');
addMessage(data);
})
})
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment