Created
June 11, 2019 15:58
-
-
Save beall49/1a48f97d991784d6f01140371fcd0b3f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* Module Code */ | |
const reqUtil = require('../utils/request-utils'); | |
const Socket = function(io) { | |
this.io = io; | |
this.io.on('connection', s => this.conn(s)); | |
}; | |
Socket.prototype.conn = function(socket) { | |
console.log(`New Socket connection made ${Date.now()}-${socket.id}`); | |
this.socket = socket; | |
this.socket.on('search', s => this.search(s)); | |
this.socket.on('disconnect', s => console.log(`disconnected`, s)); | |
}; | |
Socket.prototype.search = async function(body) { | |
const sites = await reqUtil.getSiteList(); | |
this.socket.emit('payload', { | |
id: this.socket.id, | |
sites: sites, | |
}); | |
}; | |
module.exports = Socket; | |
/* server file code */ | |
app.set('port', nodePort); | |
const io = require('socket.io').listen(server, { | |
pingTimeout: 60000, | |
}); | |
const Socket = require('./api/utils/socket-utils'); | |
new Socket(io); | |
/* client code */ | |
<html> | |
<head> | |
<title>Socket io client</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script> | |
</head> | |
<body> | |
<button class="btn" id="myButton">CLick Me</button> | |
</body> | |
</html> | |
<script> | |
var socket = io("http://thing2.test:1049"); | |
// use your socket | |
function myfunc() { | |
socket.emit("search", ({ data: 'search 3' })); | |
} | |
socket.on("payload", (data) => { | |
console.log(`data received - ${JSON.stringify(data)}`); | |
}) | |
const btn = document.getElementById("myButton"); | |
btn.addEventListener("click", () => myfunc()); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment