Answer the question
In order to leave comments, you need to log in
Why doesn't socket.io return message on the client?
Come to the server, come back to the client, no
// server
const webpack = require('webpack');
const webpackConfig = require('./webpack.config.js');
const
Koa = require('koa'),
http = require('http'),
app = new Koa(),
serve = require('koa-static'),
server = http.createServer(app.callback()),
io = require('socket.io')(server);
app.use(serve(__dirname + '/public'));
app.use(require('webpack-hot-middleware')(webpack(webpackConfig)));
io.on('connection', client => {
client.on('message', req => {
console.log(req)
io.to(req.message).emit('message', req.message);
});
});
server.listen(3000);
// client
import React from 'react';
class Chat extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
socket: this.props.socket
};
}
componentDidMount() {
this.state.socket.emit('message', {message: '123'});
this.state.socket.on('message', message => {
console.log(message)
this.setState({
messages: [message, ...this.state.messages]
});
});
}
submitMessage = event => {
if (event.keyCode === 13 && event.target.value !== '') {
this.state.socket.emit('message', {
message: event.target.value
});
event.target.value = '';
}
};
render() {
return (<div>
<ul className="chat__messages">
{this.state.messages.map((message, index) => (
<li>
{message}
</li>
))}
</ul>
<input type="text" onKeyUp={this.submitMessage} />
</div>
);
}
}
export default Chat;
Answer the question
In order to leave comments, you need to log in
Understood it was necessary to transfer to the client
io.on('connection', client => {
client.on('message', req => {
console.log(req)
client.emit('message', req.message);
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question