Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions ch4/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions ch4/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"http": "^0.0.1-security",
"nodemon": "^2.0.22",
"tslib": "^2.3.0",
"uuid": "^9.0.0",
"ws": "^8.13.0"
},
"devDependencies": {
Expand Down
124 changes: 67 additions & 57 deletions ch4/src/assets/pages/index.html
Original file line number Diff line number Diff line change
@@ -1,73 +1,83 @@
<!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">
<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>Websocket Test</title>
</head>

<body>
</head>
<body>
<h1>Message Test</h1>
<pre id="messages" style="height: 400px; overflow: scroll"></pre>
<input type="text" id="messageBox" placeholder="Type your message here"
style="display: block; width: 100%; margin-bottom: 10px; padding: 10px;" />
<button id="send" title="'Send Message!" style="width: 100%; height: 30px;">Send Message</button>

<input
type="text"
id="messageBox"
placeholder="Type your message here"
style="display: block; width: 100%; margin-bottom: 10px; padding: 10px"
/>
<button id="send" title="'Send Message!" style="width: 100%; height: 30px">
Send Message
</button>

<script>
(function () {
const sendBtn = document.querySelector('#send');
const messages = document.querySelector('#messages');
const messageBox = document.querySelector('#messageBox');
(function () {
const username = prompt('Enter your username:');
const sendBtn = document.querySelector('#send');
const messages = document.querySelector('#messages');
const messageBox = document.querySelector('#messageBox');

let ws;
let ws;
let uuid;

function showMessage(data) {
if (typeof data === 'string') {
messages.textContent += `\n\n${data}`;
} else if (data instanceof Blob) {
const reader = new FileReader();
reader.onload = () => {
messages.textContent += `\n\n${reader.result}`;
};
reader.readAsText(data);
}
messages.scrollTop = messages.scrollHeight;
messageBox.value = '';
}
function showMessage(username, text) {
messages.textContent += `\n\n${username}: ${text}`;
messages.scrollTop = messages.scrollHeight;
messageBox.value = '';
}

function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}

ws = new WebSocket('ws://localhost:3333');
ws.binaryType = 'text';
ws.onopen = () => {
console.log('Connection opended!');
}
ws.onmessage = ({ data }) => showMessage(data);
ws.onclose = function () {
ws = null;
}
ws = new WebSocket('ws://localhost:3333');
ws.binaryType = 'text';
ws.onopen = () => {
console.log('Connection opended!');
ws.send(JSON.stringify({ type: 'auth', username: username }));
};
ws.onmessage = ({ data }) => {
const message = JSON.parse(data);
if (message.type === 'auth') {
uuid = message.uuid;
} else if (message.type === 'message') {
showMessage(message.username, message.text);
}
};
ws.onclose = function () {
ws = null;
};
}

sendBtn.onclick = function () {
if (!ws) {
showMessage('No webSocket Connection');
return;
}
sendBtn.onclick = function () {
if (!ws) {
showMessage('System', 'No webSocket Connection');
return;
}

ws.send(messageBox.value);
showMessage(messageBox.value);
}
ws.send(
JSON.stringify({
type: 'message',
username: username,
text: messageBox.value,
})
);
showMessage(username, messageBox.value);
};

init();
})();
init();
})();
</script>
</body>

</html>
</body>
</html>
47 changes: 33 additions & 14 deletions ch4/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,49 @@
import express from 'express';
import { WebSocketServer } from 'ws';
import http from 'http';
import { v4 as uuidv4 } from 'uuid';
import WebSocket from 'ws';

const host = process.env.HOST ?? 'localhost';
const port = process.env.PORT ? Number(process.env.PORT) : 3333;

const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server })
const wss = new WebSocketServer({ server });

interface CustomWebSocket extends WebSocket {
dispatchEvent: (event: Event) => boolean;
}

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
wss.clients.forEach(function each(client) {
if (client != ws && client.readyState == ws.OPEN) {
client.send(data)
}
})
});
})
interface User {
username: string;
uuid: string;
ws: CustomWebSocket;
}

const users: User[] = [];

// app.get('/', (req, res) => {
// res.send({ message: 'Hello API' });
// });
wss.on('connection', function connection(ws: CustomWebSocket) {
ws.on('message', function incoming(data) {
const message = JSON.parse(data.toString());
if (message.type === 'auth') {
const newUser: User = {
username: message.username,
uuid: uuidv4(),
ws: ws,
};
users.push(newUser);
ws.send(JSON.stringify({ type: 'auth', uuid: newUser.uuid }));
} else if (message.type === 'message') {
users.forEach(function each(user) {
if (user.ws != ws && user.ws.readyState == ws.OPEN) {
user.ws.send(JSON.stringify({ type: 'message', username: message.username, text: message.text }));
}
});
}
});
});

server.listen(port, host, () => {
console.log(`[ ready ] http://${host}:${port}`);
});
});
21 changes: 20 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"dependencies": {
"v4": "^0.0.1"
}
}