我正在尝试建立一个可以连接的套接字io客户端,但无法发出或接收消息。我创建了一个Web应用程序,如果有任何用户连接,则表明有新用户连接,因此如果我打开我的应用程序它显示新用户已连接,但是当我发送消息时,它都不显示在任何一侧
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as io from 'socket.io-client';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
socket:any;
socketURL:any;
constructor(public navCtrl: NavController) {
this.socketURL = "my url";
this.socket = io(this.socketURL);
this.socket.on('connect',()=> {
console.log('connected from server');
})
this.socket.emit('createMessage', 'hello worlddddddddd');
this.socket.on('newMessage', (message)=>{
alert('new massage'+JSON.stringify(message));
}
)
}
ionViewWillleave(){
this.socket.on('disconnect',()=> {
console.log('disconnected from server');
});
}
}
答案 0 :(得分:0)
我有这种情况,它可以工作。
constructor(privatesocketService: SocketService, privatesocket: Socket){
this.socket.on('message', (data) = > {
console.log('message : ' + data);
});
}
ionViewDidLeave(){
console.log('ionViewDidLeave ChatRoomPage');
this.socketService.leaveConversation(this.conversationId);
}
ionViewDidLoad(){
console.log('ionViewDidLoad ChatRoomPage');
this.socketService.joinConversation(this.conversationId);
this.getUsers();
}
sendMessage(){
this.conversationService.sendMessage(this.conversationId, this.message);
}
import {Injectable} from '@angular/core';
import {Socket} from 'ng-socket-io';
@
Injectable()
export class SocketService {
constructor(privatesocket: Socket) {
this.socket.connect();
}
joinConversation(conversationId) {
this.socket.emit('enter-room', conversationId);
}
leaveConversation(conversationId) {
this.socket.emit('leave-room', conversationId);
}
sendMessage(conversationId) {
this.socket.emit('new-message', conversationId);
}
}