我正在为一个网站制作一个非常基本的聊天室,它使用 socket.io 来接收和发送聊天消息(socket.io 因为后端 nodejs 是使用它编写的)。
几乎一切正常,只有:
当用户发送消息时,该消息将出现在他的聊天列表中,但在刷新页面之前不会更新其他人的列表。
它是如何工作的:用户键入一条消息,该消息通过 socket.io 发送到服务器。
然后服务器用 socket.io 将消息发回给每个人,消息出现在每个人的聊天列表中。
服务器确实发回聊天消息,但只发回发件人。
我的代码(只有代码):
chat.component.ts:
Usersonline: number;
socketio;
messages = [] = [];
constructor(private socket: SocketconnectorService) {
this.socketio = socket.socket;
this.socketio.on('getOldChat', (data) => {
this.messages.push(data);
});
this.socketio.on('getChat', (data) => {
this.messages.push(data);
});
}
sendChat(chatmessage) {
console.log('Sending new message: ' + chatmessage);
this.socketio.emit('sendChat', chatmessage);
}
socketconnector.service.ts:
public socketurl = 'http://serverip:8080';
public socket;
constructor() {
this.socket = io(this.socketurl);
}
chat.component.html:
<div id="message" style="color: white">
<div *ngFor="let message of messages">
<li class="chatmessage">{{ message }}</li>
</div>
</div>
<div class="input-box">
<input class="input-box-inside" #chatmessage (keyup.enter)="sendChat(chatmessage.value);chatmessage.value='' ">
<button id="input-box-send" (click)="sendChat(chatmessage.value)" type="button"><i class="fa fa-paper-plane"></i></button>
</div>