Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const app = require('http').createServer(handler)
- const io = require('socket.io')(app)
- const fs = require('fs')
- let clients = []
- app.listen(8080)
- function handler(req, res) {
- if (req.url === '/') {
- fs.readFile(__dirname + '/index.html', (err, data) => {
- if (err) {
- res.writeHead(500)
- return res.end('Error loading index.html')
- } else {
- res.writeHead(200)
- res.end(data)
- }
- })
- } else if (req.headers.referer) {
- fs.readFile(__dirname + req.url, (err, data) => {
- if (err) console.log('Error loading ' + req.url)
- else {
- res.writeHead(200)
- res.end(data)
- }
- })
- }
- }
- io.on('connection', (socket) => {
- console.log('connection')
- let client = {}
- client.socket = socket
- socket.on('userlist', (data) => {
- let canConnect = true
- if(clients.map(x => x.username).indexOf(data) >= 0){
- canConnect = false
- }
- socket.emit('canConnect', canConnect)
- })
- socket.on('username', (data) => {
- client.username = data
- clients.push(client)
- clients.forEach((e) => {
- e.socket.emit('userslist', clients.map(x => x.username))
- })
- })
- socket.on('message', (data) => {
- sendMessage(data)
- })
- socket.on('disconnect', () => {
- console.log('user disconnected')
- const i = clients.map(x => x.socket).indexOf(socket)
- clients.splice(i, 1)
- clients.forEach((e) => {
- e.socket.emit('userslist', clients.map(x => x.username))
- })
- })
- });
- function sendMessage(data) {
- if(data.to){
- sendPrivateMessage(data)
- return
- }
- clients.forEach((e) => {
- e.socket.emit('message', getDate() + ' ' + data.username + ' : ' + data.message)
- })
- }
- function sendPrivateMessage(data){
- const sendTo = clients.map( x => x.username).indexOf(data.to)
- if(sendTo < 0){}
- //tutaj error nie znaleziono usera
- else{
- const sendToSocket = clients[sendTo].socket
- const obj = {}
- obj.message = getDate() + ' ' + data.username + ' : ' + data.message
- obj.from = data.username
- sendToSocket.emit('privatemessage', obj)
- obj.from = data.to
- obj.echo = true
- clients[clients.map(x => x.username).indexOf(data.username)].socket.emit('privatemessage', obj)
- }
- }
- function getDate() {
- const date = new Date()
- const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
- const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
- const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
- return hours + ":" + minutes + ":" + seconds
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement