package.json
{
"name": "react-socketio",
"version": "0.1.0",
"private": true,
"dependencies": {
"concurrently": "^4.0.1",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-scripts": "1.1.5",
"socket.io-client": "^2.1.1"
},
"scripts": {
"start": "concurrently --kill-others \"node server/server.js\" \"react-scripts start\"",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {}
}
------------------------------------------------------
server/package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3",
"socket.io": "^2.1.1"
}
}
----------------------------------------
server.js
const express = require('express');
const socket = require('socket.io');
const app = express();
//server entry port
const port = 5000;
server = app.listen(port, function(){
console.log('server is running on port ', port)
});
let clientNum = 0;
io = socket(server);
io.on('connection', (socket) => {
clientNum++;
let currentTime = new Date();
const socketId = socket.id;
const connectionRes = currentTime.toLocaleString() + ' ' +
socketId + ' connected. ' +clientNum.toString() + ' online';
console.log(connectionRes);
//send to self when connected
io.to(socketId).emit('server_connect', connectionRes);
//response to client send event
socket.on('client_chat', data=>{
currentTime = new Date();
//send to all clients
//io.emit('server', 'server response');
//send to everyone except self
socket.broadcast.emit('server_chat',
{
name: data.name==''? socketId.toString() : data.name,
message: data.message,
});
})
//client leaves
socket.on('disconnect', () => {
clientNum--;
currentTime = new Date();
console.log(currentTime.toLocaleString(),
'client disconnected. users', clientNum);
})
});
---------------------------------------
app.js
import React, { Component } from 'react';
import './App.css';
import io from 'socket.io-client'
class App extends Component {
constructor(props) {
super(props)
this.state={
connectionStatus: '',
chat: [],
name: '',
message: '',
}
//connect to server
this.socket = io('localhost:5000');
this.socket.on('server_connect', data=>{
this.setState({connectionStatus: data});
});
//append received message to chat
this.socket.on('server_chat', data=>{
this.setState(prev=>
{
const newChat = <div>
<span style={{color: 'blue'}}>{data.name}</span>
<span>: {data.message}</span>
</div>
return {
chat: [...prev.chat].concat(newChat),
}
});
});
}
send=()=>{
this.socket.emit('client_chat', {
name: this.state.name,
message: this.state.message,
});
//append my message to chat
this.setState(prev=>
{
const newChat = <div>
<span style={{color: 'green'}}>me</span>
<span>: {this.state.message}</span>
</div>
return {
chat: [...prev.chat].concat(newChat),
}
});
}
changeName=(e)=>{
this.setState({name: e.target.value});
}
changeMessage=(e)=>{
this.setState({message: e.target.value});
}
componentDidMount(){
console.log(JSON.stringify(process.env));
}
render() {
const chatDialog = this.state.chat.map((item,index)=>{
return <div key={index}>{item}</div>
})
return (
<div>
{this.state.connectionStatus} <br/>
<div style={{height:'300px',
backgroundColor:'lightGrey',
overflow:'scroll'}}>
{chatDialog}
</div>
<input placeholder='Name'
onChange={(e)=>this.changeName(e)}></input>
<br/>
<textarea style={{width:'350px', height:'100px'}} placeholder='Message'
onChange={(e)=>this.changeMessage(e)}></textarea>
<br/>
<button onClick={()=>this.send()}>send</button>
</div>
);
}
}
export default App;
--------------------------------------------
reference:
No comments:
Post a Comment