我无法从本地主机连接到同一房间。 这些消息显示在服务器的控制台中,但没有出现在其他选项卡中。 这是我的代码。你能帮忙吗?
这是我的服务器“逻辑”:
var nsp = io.of('/my-namespace');
nsp.on('connection', function(socket){
socket.join('ID');
//console.log("connected!" +socket.toString());
socket.on('Newmessage', function(msg){
console.log(socket.client + " said "+ msg);
let time = moment(new Date()).format("HH:mm:ss").toString();
// socket.broadcast.emit('message', msg,time);
io.to('ID').emit('Newmessage', msg,time);
console.log(socket.client.id + " said "+ msg);
这是我的客户“逻辑”:
获取消息
componentDidMount(){
this.state.socket = io('/my-namespace');
// this.state.io = io();
this.state.socket.on("Newmessage",
(msg,time)=>{
alert("new message incoming!");
this.AppendMessage(msg,time,false);
});
}
发布消息:
PostMessage = (chat) => {
let dateRecived = -1;
let message = this.state.inputValue;
let x = true;
fetch('/api/world', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ post: this.state.inputValue }),
})
.then(res => res.text())//response type
.then(time => this.AppendMessage(this.state.inputValue ,time,true))
.then((res)=>{ this.state.socket.emit("Newmessage",message); console.log(message); return res;})
.finally(res => res = 1); //log the data;
}