以下代码仅发出一次数据 . 我不确定它是否会发出一次因为我认为数据没有从前端(角度2)正确发送到后端(nodeJs) .
chat.component.ts的前端代码:
ngOnInit() {
const sendData = {
username: this.username,
message: this.message
};
const socket = socketIo('http://localhost:3000');
socket.emit('chat message', {
username: 'sendData.username',
message: sendData.message
});
socket.on('chat message', function(msg){
const messageArea = document.getElementById('output');
messageArea.innerHTML +="<strong>" + socket.username + "</strong> : " + socket.message + "\n";
console.log(msg.username + 'lmemons');
});
}
后端代码:
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg){
console.log('///////////////////////////////');
io.emit('chat message', msg.username + ': ' + msg.message);
console.log('--------------------------');
});
});
代码运行一次,由console.logs显示 . 它每次都只是未定义的 .
我试过用:
socket.on('chat message',function(msg){...
在外面
io.on('connection',function(socket){
但它有套接字错误声称它是未定义的 .
基本上我想将数据附加到每个连接的所有套接字的文本区域 .
我正在使用这个https://socket.io/get-started/chat/教程寻求帮助 .