Last active
February 23, 2021 17:02
-
-
Save oddmario/550d8a51e7aeb3ae5e622be977cc042b to your computer and use it in GitHub Desktop.
Sample WebSocket server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const WebSocket = require('ws'); | |
const wss = new WebSocket.Server({ port: 25595 }); | |
wss.on('connection', function connection(ws, req) { | |
var timer; | |
var firstMessageSent = false; | |
var areYouSureAsked = false; | |
const ip = req.socket.remoteAddress; | |
console.time(ip + " stayed for"); | |
ws.send("Welcome friend!"); | |
console.log(ip + " connected."); | |
ws.on('message', function incoming(message) { | |
if(!firstMessageSent && message.toLowerCase() !== "yes" && message.toLowerCase() !== "no") { | |
firstMessageSent = true; | |
} | |
if(firstMessageSent) { | |
if(message.toLowerCase() == "yes") { | |
if(!areYouSureAsked) { | |
ws.send("Wow! This mean I can hear you!"); | |
} else { | |
ws.send("How come :c I'm pretty sure you said it!"); | |
areYouSureAsked = false; | |
} | |
} else if(message.toLowerCase() == "no") { | |
if(!areYouSureAsked) { | |
ws.send("Are you sure??! ;o"); | |
areYouSureAsked = true; | |
} else { | |
ws.send("Ikr! I know you said it."); | |
areYouSureAsked = false; | |
} | |
} else { | |
ws.send("Did you just say '" + message + "' ?"); | |
} | |
} else { | |
if(message.toLowerCase() == "yes") { | |
ws.send("You can't say 'yes' yet o.o"); | |
} | |
if(message.toLowerCase() == "no") { | |
ws.send("You can't say 'no' yet o.o"); | |
} | |
} | |
if(message.toLowerCase() == "bye") { | |
ws.send("Bye Bye!"); | |
ws.terminate(); | |
} | |
console.log('Received: %s', message); | |
}); | |
ws.on('close', function close(code, reason) { | |
console.log(ip + " disconnected."); | |
clearInterval(timer); | |
console.timeEnd(ip + " stayed for"); | |
}); | |
setTimeout(function() { | |
ws.send("Try answering with 'yes' or 'no' when you are asked whether you said something or not."); | |
}, 4000); | |
timer = setInterval(function() { | |
console.log(ip + " is still connected..."); | |
}, 5000); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment