Skip to content

Commit

Permalink
Mudando estrategia: usando lib socket.io pra fazer a magica
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucas Chuairi Cruz committed Aug 23, 2018
1 parent 606e0d9 commit aafff1e
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 152 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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
88 changes: 14 additions & 74 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -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, '&amp;').replace(/</g, '&lt;')
.replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

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');
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
1 change: 1 addition & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,5 @@
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
</html>
77 changes: 4 additions & 73 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* global alert WebSocket */
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import configureStore from './store/configureStore'
Expand All @@ -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({
Expand All @@ -100,20 +41,10 @@ class App extends Component {
renderChatRooms() {
if (this.state.username) {
return (
<div>
<div className="chat">
<ChatHeader username={this.state.username} />
<ChatList />
<Chat />
</div>

{/* <form onSubmit={this.onMsgSubmit.bind(this)}>
<label>
Msg:
<input type="text" value={this.state.msg} onChange={this.onMsgChange.bind(this)} />
</label>
<input type="submit" value="Submit" />
</form> */}
<div className="chat">
<ChatHeader username={this.state.username} />
<ChatList />
<Chat />
</div>
)
}
Expand Down
92 changes: 88 additions & 4 deletions src/components/Chat/index.js
Original file line number Diff line number Diff line change
@@ -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 (
<div className="chat-room">
<div className="chat-room__messages">
{!this.props.chat.loading && !this.props.chat.id && this.props.chat.messages.length === 0 && <span>Nenhum chat selecionado</span>}
{this.props.chat.loading && <span>carregando chat</span>}
{!this.props.chat.loading && this.props.chat.id && <span>mensagens chat{this.props.chat.id}</span>}
{!this.props.chat.loading && this.props.chat.id &&
this.state.msgs.map((msg, i) => <div key={i}>{msg}</div> )
}
</div>

<div className="chat-room__input__wrapper">
<input placeholder="escreva uma mensagem" className="chat-room__input"/>
<form onSubmit={this.onMsgSubmit.bind(this)}>
<input
placeholder="escreva uma mensagem"
className="chat-room__input"
value={this.state.msg}
onChange={this.onMsgChange.bind(this)} />
{/* <input type="submit" value="Submit" /> */}
</form>
</div>
</div>
)
Expand All @@ -30,5 +115,4 @@ function mapStateToProps(state) {
})
}

export default connect(mapStateToProps)(Chat)

export default connect(mapStateToProps)(Chat)

0 comments on commit aafff1e

Please sign in to comment.