You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
matrix-chat/api.js

62 lines
2.4 KiB
JavaScript

4 years ago
const ws = require('ws')
//WS server
const wss = new ws.Server({
port: 8090,
4 years ago
perMessageDeflate: {
zlibDeflateOptions: {
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
},
clientNoContextTakeover: true,
serverNoContextTakeover: true,
serverMaxWindowBits: 10,
concurrencyLimit: 10,
threshold: 1024
4 years ago
}
});
//WS handler
4 years ago
let user = [];
wss.on('connection', (ws, req) => {
4 years ago
let thisuser = ""
console.log(`${req.socket.remoteAddress} connected`)
4 years ago
ws.on('message', msgJSON => {
let msg = JSON.parse(msgJSON)
console.log(`${req.socket.remoteAddress} (${thisuser}) => ${msgJSON}`)
4 years ago
if (msg.type === 'message')
if (thisuser === ""){
ws.send(JSON.stringify({type: "error", content: "please login before writing"}))
ws.send('{"type":"route","path":"/login"}')
}else if (msg.content.text === "")
ws.send(JSON.stringify({type: "error", content: "your message was empty"}))
else{
msg.content.user = thisuser
msg.content.text = msg.content.text.replace(/</g, "&lt").replace(/>/g, "&gt").replace(/\n/g, "<br>")
wss.clients.forEach(client => client.send(JSON.stringify(msg)))
4 years ago
}
4 years ago
else if (msg.type === 'login' && msg.content.user !== ""){
if (msg.content.user.length >= 20) ws.send(JSON.stringify({type: "error", content: "username is too long"}))
else if (msg.content.user === "you" || user.indexOf(msg.content.user) !== -1)
ws.send(JSON.stringify({type: "error", content: "username already exist"}))
4 years ago
else{
thisuser = msg.content.user
user.push(msg.content.user)
ws.send('{"type":"route","path":"/chat"}')
ws.send(JSON.stringify({type: "info", username: thisuser}))
4 years ago
wss.clients.forEach(client =>
client.send(JSON.stringify({type: "room", name: "open chat", user: user})))
}
4 years ago
}
4 years ago
})
ws.on('close', () => {
user.splice(user.indexOf(thisuser), 1);
console.log(`${req.socket.remoteAddress} (${thisuser}) closed`)
})
4 years ago
ws.send(JSON.stringify({type: "info", time: Date.now(), content: "connected"}))
4 years ago
})