问题描述
我正在使用服务器和客户端之间的基本Web套接字连接来创建简单的聊天应用程序。
我进行设置的方式应该像这样:
- 客户端在传递
send_message
对象的同时发出_new_message
事件 - 服务器监听
send_message
事件,当它启动时,它会处理数据并将其添加到数据库中,然后将_new_message
对象发送回客户端 - 客户端获取
_new_message
对象,将其添加到redux
存储中并更新组件,从而将新消息呈现给用户。
第一步和第二步工作正常。服务器可以获取消息并将其添加到数据库中,然后使用send
函数将其返回给客户端。问题在于客户端出于某种原因未监听send_message
事件。
这是后端代码(使用Flask用Python编写):
@socket.on("send_message")
def handleMessage(_new_message):
print(_new_message)
message = chat.send_message(msg) # Doesnt affect the process much. Ive tried with and without this line.
send(str(_new_message),broadcast=True)
socket.emit("send_message",_new_message)
return None
这是React组件:
import React,{ Component } from "react"
import { MdPhotoLibrary,mdsend } from "react-icons/md"
import io from "socket.io-client"
import { connect } from 'react-redux'
import { getGeneralData } from "../../redux/actions/GeneralActions"
import { getMessages,getConversations } from "../../redux/actions/ChatActions"
let socket = io.connect("http://0.0.0.0:5000")
class Conversation extends Component {
constructor(props) {
super(props)
this.state = {
_new_message: {
_conversation_id: this.props.match.params._conversation_id,_message_type_id: "",_message: ""
}
}
}
componentDidMount = () => {
socket.on("send_message",_new_message => {
console.log(_new_message)
})
this.props.getGeneralData()
this.props.getMessages()
this.props.getConversations()
}
handleChange = e => {
// Updates state
}
handleSubmit = e => {
e.preventDefault()
this.setState({
_new_message: {
...this.state._new_message,_user_id: this.props.user.currentUser._id
}
},() => {
this.props.addingMessage()
socket.emit("send_message",this.state._new_message)
})
}
render() {
return(
<div className="conversation">
<div className="messages">
</div>
<div className="controls">
<input name="_message" type="text" onChange={e => this.handleChange(e)} />
<span>
<label><MdPhotoLibrary /></label>
<input name="_message" type="file" onChange={e => this.handleChange(e)}
/>
</span>
<button onClick={e => this.handleSubmit(e)}><mdsend /></button>
</div>
</div>
)
}
}
const mapStatetoProps = state => {
# Maps state to props
}
const mapdispatchToProps = dispatch => {
# Maps dispatch to props
}
export default connect(mapStatetoProps,mapdispatchToProps)(Conversation)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)