diff --git a/README.md b/README.md index 8e9fc84..d63725a 100644 --- a/README.md +++ b/README.md @@ -2,4 +2,6 @@ 2) Node Websocket: https://medium.com/@martin.sikora/node-js-websocket-simple-chat-tutorial-2def3a841b61 3) npm start rodando client + server só pra simplificar o processo. 4) eslint -> airbnb -5) redux -> pra compartilhar estados dos chats selecionados. \ No newline at end of file +5) redux -> pra compartilhar estados dos chats selecionados. +6) mudança de planos -> socket.io + - maior facilidade pra controlar a conexão tanto do no front quanto no back end \ No newline at end of file diff --git a/api/server.js b/api/server.js index d718c43..bc4c2c2 100644 --- a/api/server.js +++ b/api/server.js @@ -1,81 +1,21 @@ -"use strict"; +var app = require('express')(); +var http = require('http').Server(app); +var io = require('socket.io')(http); -var webSocketsServerPort = 3001; -var webSocketServer = require('websocket').server; -var http = require('http'); +io.on('connection', function(socket) { + console.log('a user connected'); -var history = [ ]; -var clients = [ ]; - -function htmlEntities(str) { - return String(str) - .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); -} - -var server = http.createServer(function(request, response) { - // Not important for us. We're writing WebSocket server, - // not HTTP server -}); + socket.on('disconnect', function() { + console.log('user disconnected'); + }); -server.listen(webSocketsServerPort, function() { - console.log((new Date()) + " Server is listening on port " - + webSocketsServerPort); -}); + socket.on('message', function(msg) { + console.log('message: ' + msg); + io.emit('message', msg); + }); -var wsServer = new webSocketServer({ - httpServer: server }); -wsServer.on('request', function(request) { - console.log((new Date()) + ' Connection from origin ' + request.origin + '.'); - - var connection = request.accept(null, request.origin); - var index = clients.push(connection) - 1; - var userName = false; - - console.log((new Date()) + ' Connection accepted.'); - // send back chat history - if (history.length > 0) { - connection.sendUTF( - JSON.stringify({ type: 'history', data: history} )); - } - // user sent some message - connection.on('message', function(message) { - // accept only text - if (message.type === 'utf8') { - - // first message sent by user is their name - if (userName === false) { - userName = htmlEntities(message.utf8Data); - console.log((new Date()) + ' User is known as: ' + userName); - } else { // log and broadcast the message - console.log((new Date()) + ' Received Message from ' - + userName + ': ' + message.utf8Data); - - // we want to keep history of all sent messages - var obj = { - time: (new Date()).getTime(), - text: htmlEntities(message.utf8Data), - author: userName, - }; - history.push(obj); - history = history.slice(-100); - // broadcast message to all connected clients - var json = JSON.stringify({ type:'message', data: obj }); - for (var i=0; i < clients.length; i++) { - clients[i].sendUTF(json); - } - } - } - }); - // user disconnected - connection.on('close', function(connection) { - if (userName !== false) { - console.log((new Date()) + " Peer " - + connection.remoteAddress + " disconnected."); - // remove user from the list of connected clients - clients.splice(index, 1); - } - }); +http.listen(3001, function() { + console.log('listening on *:3001'); }); \ No newline at end of file diff --git a/package.json b/package.json index 3104226..c527c3c 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "react-scripts": "1.1.4", "redux": "^4.0.0", "redux-thunk": "^2.3.0", + "socket.io": "^2.1.1", "websocket": "^1.0.26" }, "scripts": { diff --git a/public/index.html b/public/index.html index ed0ebaf..4c04309 100644 --- a/public/index.html +++ b/public/index.html @@ -37,4 +37,5 @@ To create a production bundle, use `npm run build` or `yarn build`. --> + diff --git a/src/App.js b/src/App.js index c8a54d7..7b1f769 100644 --- a/src/App.js +++ b/src/App.js @@ -1,4 +1,3 @@ -/* global alert WebSocket */ import React, { Component } from 'react' import { Provider } from 'react-redux' import configureStore from './store/configureStore' @@ -13,68 +12,10 @@ class App extends Component { constructor() { super() this.state = { - msg: '', username: 'lusac' } } - componentDidMount() { - // this.wsConnect() - } - - wsConnect() { - let connection = new WebSocket('ws://127.0.0.1:3001') - - connection.onopen = function () { - console.log('WS OPENED!') - } - - connection.onerror = function (error) { - alert(`WS ERROR: ${error}`) - } - - connection.onmessage = function (message) { - // try to decode json (I assume that each message - // from server is json) - try { - var json = JSON.parse(message.data) - alert(json) - } catch (e) { - alert('SERVER NAO RETORNOU JSON') - } - - if (json.type === 'color') { - // pass... - } else if (json.type === 'history') { // entire message history - for (var i=0; i < json.data.length; i++) { - console.log(json.data[i].author, json.data[i].text, json.data[i].color, new Date(json.data[i].time)) - } - } else if (json.type === 'message') { // it's a single message - console.log(json.data.author, json.data.text, json.data.color, new Date(json.data.time)) - } else { - console.log('Hmm..., I\'ve never seen JSON like this:', json) - } - } - - this.setState({ - connection: connection - }) - } - - onMsgChange(e) { - this.setState({ - msg: e.target.value - }) - } - - onMsgSubmit(e) { - e.preventDefault() - this.state.connection.send(this.state.msg) - this.setState({ - msg: '' - }) - } - onUsernameSubmit(e) { e.preventDefault() this.setState({ @@ -100,20 +41,10 @@ class App extends Component { renderChatRooms() { if (this.state.username) { return ( -
-
- - - -
- - {/*
- - -
*/} +
+ + +
) } diff --git a/src/components/Chat/index.js b/src/components/Chat/index.js index 252acbb..6a8a0ab 100644 --- a/src/components/Chat/index.js +++ b/src/components/Chat/index.js @@ -1,19 +1,104 @@ +/* global alert WebSocket */ import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' +import socketIOClient from 'socket.io-client' export class Chat extends React.Component { + constructor() { + super() + this.state = { + msg: '', + msgs: [], + connection: null + } + } + + componentDidMount() { + this.wsConnect() + } + + wsConnect() { + var socket = socketIOClient('http://localhost:3001') + + this.setState({ + socket: socket + }) + + socket.on('message', (msg) => { + this.setState({ + msgs: [...this.state.msgs, msg] + }) + }) + + // let connection = new WebSocket('ws://127.0.0.1:3001') + + // connection.onopen = function () { + // console.log('WS OPENED!') + // } + + // connection.onerror = function (error) { + // alert(`WS ERROR: ${error}`) + // } + + // connection.onmessage = function (message) { + // // try to decode json (I assume that each message + // // from server is json) + // try { + // var json = JSON.parse(message.data) + // alert(json) + // } catch (e) { + // alert('SERVER NAO RETORNOU JSON') + // } + // debugger; + // if (json.type === 'color') { + // // pass... + // } else if (json.type === 'history') { // entire message history + // for (var i=0; i < json.data.length; i++) { + // console.log(json.data[i].author, json.data[i].text, json.data[i].color, new Date(json.data[i].time)) + // } + // } else if (json.type === 'message') { // it's a single message + // console.log(json.data.author, json.data.text, json.data.color, new Date(json.data.time)) + // } else { + // console.log('Hmm..., I\'ve never seen JSON like this:', json) + // } + // } + } + + onMsgChange(e) { + this.setState({ + msg: e.target.value + }) + } + + onMsgSubmit(e) { + e.preventDefault() + this.state.socket.emit('message', this.state.msg) + this.setState({ + msg: '' + }) + } + render() { return (
{!this.props.chat.loading && !this.props.chat.id && this.props.chat.messages.length === 0 && Nenhum chat selecionado} {this.props.chat.loading && carregando chat} - {!this.props.chat.loading && this.props.chat.id && mensagens chat{this.props.chat.id}} + {!this.props.chat.loading && this.props.chat.id && + this.state.msgs.map((msg, i) =>
{msg}
) + }
- +
+ + {/* */} +
) @@ -30,5 +115,4 @@ function mapStateToProps(state) { }) } -export default connect(mapStateToProps)(Chat) - +export default connect(mapStateToProps)(Chat) \ No newline at end of file