Skip to content

Instantly share code, notes, and snippets.

@marcodali
Last active November 26, 2023 23:20
Show Gist options
  • Save marcodali/f71c88953f648d9c90fe25fd254f88c4 to your computer and use it in GitHub Desktop.
Save marcodali/f71c88953f648d9c90fe25fd254f88c4 to your computer and use it in GitHub Desktop.
Developers nicknames
// COPY&PASTE code starts here
const happyEmoticons = [
'πŸ˜€', '😁', 'πŸ˜‚', '🀣', 'πŸ˜ƒ', 'πŸ˜„', 'πŸ˜…', 'πŸ˜†',
'πŸ˜‰', '😊', 'πŸ˜‹', '😎', '😍', '😘', 'πŸ˜—', 'πŸ˜™',
'😚', 'πŸ™‚', 'πŸ€—', '🀩', '😏', '😌', 'πŸ˜›', '😜',
'😝', '🀀', 'πŸ€‘', '😲', '😳', 'πŸ€ͺ', 'πŸ₯³', '😈',
]
const happyEmoticonsLength = happyEmoticons.length
const socketMatchDevelopers = new Map()
const socketMatchFlag = new Map()
const developers = {}
// Send the list of developers to all connected sockets
const broadcastDevelopersToAllConnectedSockets = () => {
const devData = JSON.stringify(Object.values(developers))
for (const socket of socketMatchDevelopers.keys()) {
socket.send(devData)
}
}
// Get a random emoticon
const getRandomEmoticon = () => happyEmoticons[
Math.floor(Math.random() * happyEmoticonsLength)
]
const getCountryData = async (ipAddress) => {
try {
const response = await axios.get(`http://ip-api.com/json/${ipAddress}`)
return response.data.countryCode
} catch (error) {
console.error('Error fetching country data:', error)
// NP = Nepal, BT = Bhutan
return Math.random() > 0.5 ? 'NP' : 'BT'
}
}
const getCountryEmoji = (countryCode) => countryCode.replace(/./g,(ch)=>String.fromCodePoint(0x1f1a5+ch.toUpperCase().charCodeAt()))
const cleanString = (str) => str.replace(/[^a-zA-Z]+/g, '')
wss.on('connection', async (ws, req) => {
// Delete the recently disconnected socket from the hashmap
ws.on('close', () => {
const deadDevelopers = socketMatchDevelopers.get(ws)
const msg = `This socket was linked to ${Array.from(deadDevelopers).join(', ') || 'None'}, but has gone away`
socketMatchDevelopers.delete(ws)
socketMatchFlag.delete(ws)
for (const developer of deadDevelopers) {
developers[developer].state = 'πŸ”΄'
}
console.log(
msg + ', there',
socketMatchDevelopers.size <= 1 ? 'is' : 'are',
socketMatchDevelopers.size == 0 ? 'None' : socketMatchDevelopers.size,
'left',
)
broadcastDevelopersToAllConnectedSockets()
})
// Handle errors
ws.on('error', error => console.error('Megaerror happened:', error))
// Handle received messages
ws.onmessage = (msg) => {
const username = cleanString(msg.data)
console.log('message received:', username)
if (username === 'Mirna') {
// delete everything but me
socketMatchDevelopers.values().forEach(set => set.clear())
Object.keys(developers).forEach(key => delete developers[key])
}
developers[username] = {
name: username,
state: getRandomEmoticon(),
from: socketMatchFlag.get(ws),
}
socketMatchDevelopers.get(ws)?.add(username)
broadcastDevelopersToAllConnectedSockets()
}
// Add the recently connected socket to the Map
const ipAddress = (req.headers['x-forwarded-for']?.split(',')[0].trim()) || req.socket.remoteAddress
const countryCode = await getCountryData(ipAddress)
const emoji = getCountryEmoji(countryCode)
if (!socketMatchDevelopers.has(ws)) {
socketMatchDevelopers.set(ws, new Set())
console.log('New socket online, new size is =', socketMatchDevelopers.size)
}
if (!socketMatchFlag.has(ws)) {
socketMatchFlag.set(ws, emoji)
}
// Send the list of developers to the recently connected socket
ws.send(JSON.stringify(Object.values(developers)))
})
// COPY&PASTE code ends here
@marcodali
Copy link
Author

Example Web Socket Server backend-project for Mirna.Cloud demonstration purposes

Description

This JavaScript code snippet sets up a WebSocket server to manage developer connections. It defines:

  • happyEmoticons: An array of emoticon strings.
  • socketMatchDevelopers: A map to track developer WebSocket connections.
  • socketMatchFlag: A map to track the country flags associated with each WebSocket.
  • developers: An object to store developer data.

Key functionalities include:

  • broadcastDevelopersToAllConnectedSockets(): Broadcasts the list of developers to all connected clients.
  • getRandomEmoticon(): Returns a random emoticon from the happyEmoticons array.
  • getCountryData(ipAddress): Asynchronously fetches the country code from the IP-API service.
  • getCountryEmoji(countryCode): Returns the emoji flag corresponding to a given country code.

In the wss.on('connection') event:

  • On socket close, it cleans up the socketMatchDevelopers and socketMatchFlag maps and updates the developers' states.
  • On error, logs the error.
  • On message, updates the developer's information with a random emoticon and associated country flag.
  • For new connections, it fetches the country data and sets up the maps, then sends the list of developers to the new connection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment