Skip to content

Instantly share code, notes, and snippets.

@davit-khaburdzania
Created January 28, 2018 09:50
Show Gist options
  • Save davit-khaburdzania/74e859be6f26e29f36e5ff9a87d5df3e to your computer and use it in GitHub Desktop.
Save davit-khaburdzania/74e859be6f26e29f36e5ff9a87d5df3e to your computer and use it in GitHub Desktop.
socket.js
import { Socket, Presence } from './Phoenix'
const TIMEOUT = 10000
const URL = 'ws://localhost:4000/socket'
const ROOM = 'user_chats:13'
export default (user, onChat) => {
// construct a socket
console.time('connection to socket');
const socket = new Socket(URL, { params: { token: "V3RGTm9GbjRFdFRldzE4QzNRSU9UUT09" }})
// configure the event handlers
socket.onError(event => console.log('Cannot connect.'))
socket.onClose(event => console.log('Goodbye.'))
// open a connection to the server
socket.connect()
// configure a channel into a room - https://www.youtube.com/watch?v=vWFX4ylV_ko
// const chan = socket.channel(ROOM)
console.timeEnd('connection to socket');
console.time('connection to channel');
const chan = socket.channel("location")
// join the channel and listen for admittance
chan.join()
.receive('error', errors => console.log('Error: ', errors))
.receive('ignore', () => console.log('Access denied.'))
.receive('ok', (params) => {
console.timeEnd('connection to channel');
console.time('sending message to channel');
send({lat: 1.3994949, lng: 0.4555555, distance: 100000})
})
.receive('timeout', () => console.log('Must be a MongoDB.'))
// add some channel-level event handlers
chan.onError(event => console.log('Channel blew up.'))
chan.onClose(event => console.log('Channel closed.'))
// when we receive a new chat message, just trigger the appropriate callback
chan.on('new:msg', msg => onChat && onChat(msg))
// you can can listen to multiple types
chan.on('user:entered', msg => console.log('say hello to ', msg))
// a function to shut it all down
const close = () => socket.disconnect()
// a function to send a message
const send = (data) => {
chan.push('get:nearby', data, TIMEOUT)
.receive('ok', (msg) => console.timeEnd('sending message to channel'))
.receive('error', (reasons) => console.log('flop', reasons))
.receive('timeout', () => console.log('slow much?'))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment