Commit 34de1df7 authored by Omar Elkadi's avatar Omar Elkadi
Browse files

websocket on port 6868 + ws message client on server

parent 38160451
This diff is collapsed.
......@@ -22,7 +22,8 @@
"nodemon": "^2.0.6",
"systeminformation": "^5.6.12",
"ts-node": "^9.1.0",
"typescript": "^4.1.2"
"typescript": "^4.1.2",
"ws": "^7.5.0"
},
"nodemonConfig": {
"ignore": [
......@@ -39,6 +40,7 @@
},
"devDependencies": {
"@types/cors": "^2.8.10",
"@types/multer": "^1.4.5"
"@types/multer": "^1.4.5",
"@types/ws": "^7.4.5"
}
}
<h1>Real Time Messaging</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>
<script>
(function() {
const sendBtn = document.querySelector('#send');
const messages = document.querySelector('#messages');
const messageBox = document.querySelector('#messageBox');
let ws;
function showMessage(message) {
messages.textContent += `\n\n${message}`;
messages.scrollTop = messages.scrollHeight;
messageBox.value = '';
}
function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
ws = new WebSocket('ws://localhost:6868');
ws.onopen = () => {
console.log('Connection opened!');
}
ws.onmessage = ({ data }) => showMessage(data);
ws.onclose = function() {
ws = null;
}
}
sendBtn.onclick = function() {
if (!ws) {
showMessage("No WebSocket connection :(");
return ;
}
ws.send(messageBox.value);
showMessage(messageBox.value);
}
init();
})();
</script>
\ No newline at end of file
......@@ -5,6 +5,7 @@ import { patientRoutes } from "./routes/patientRoutes";
import { dataRoutes } from "./routes/dataRoutes";
import * as cors from "cors";
import multer = require("multer");
import WebSocket = require("ws");
// Express Server Typescript
class Server {
......@@ -54,5 +55,26 @@ class Server {
}
} // Server
const http = require('http');
const port = 6969;
const wSserver = http.createServer(express);
const wss = new WebSocket.Server({ port: 6868 })
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
console.log(data)
}
})
})
})
wSserver.listen(port, function() {
console.log(`Server is listening on ${port}!`)
})
const server = new Server();
server.start(server.serv, 3000); // server.serv is httpServer, 3000 Portnumber
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment