Last active
February 4, 2019 09:53
-
-
Save alkhachatryan/23de3b01eac903799bbe5e93b384ca8c to your computer and use it in GitHub Desktop.
Socket.io (server+client) and Express based Sample chat system
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
/** | |
* Socket io client | |
* */ | |
socket = require('socket.io-client')(window.location.hostname + ':9090'); | |
/** | |
* Chat Functionalities | |
*/ | |
chat = { | |
addMessageElement: (element) => { | |
// Add Message DOM element using element var info | |
}, | |
pushMessageToSocket: () => { | |
var data = { | |
message: $("#chatTextarea").val().trim() | |
}; | |
socket.emit('chat-message', data); | |
$("#chatTextarea").val(''); | |
} | |
}; | |
/** | |
* Events | |
* */ | |
require('event-handler'); |
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
socket.on('connect', () => { | |
// User connected | |
}); | |
socket.on('chat-message', (data) => { | |
chat.addMessageElement(data); | |
}); | |
socket.on('disconnect', () => { | |
// User disconnected | |
}); |
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 express = require('express')(); | |
const server = require('http').Server(express); | |
const io = require('socket.io')(server); | |
io.on('connection', function (socket) { | |
console.log("new client connected"); | |
socket.on('chat-message', function (data) { | |
io.emit('chat-message', data); | |
}); | |
socket.on('user-join', function(data) { | |
io.emit('user-join', data); | |
}); | |
socket.on('disconnect', function(data) { | |
}); | |
}); | |
server.listen(9090, function () { | |
console.log('socket.io server listen at 9090'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment