Reputation: 1
websocketservice
import { Injectable } from '@angular/core';
import { WebSocketSubject } from 'rxjs/webSocket';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class WebSocketService {
public socket$: WebSocketSubject<any>;
constructor() {
// Initialize WebSocket connection
this.socket$ = new WebSocketSubject({
url: 'ws://localhost:8088/ws', // Replace with your WebSocket URL
deserializer: (e) => {
// Attempt to parse JSON, or return plain text if parsing fails
try {
return JSON.parse(e.data);
} catch (error) {
console.warn('Received non-JSON message:', e.data);
return e.data; // Return as plain text if not JSON
}
},
serializer: (msg) => {
// Serialize outgoing messages to JSON (assuming you want to send JSON)
return JSON.stringify(msg);
},
});
// Subscribe to the WebSocket messages
this.socket$.pipe(
catchError((error) => {
console.error('WebSocket error:', error);
return of(null); // Gracefully handle errors
})
).subscribe((message) => {
if (typeof message === 'string') {
// Handle plain text message
console.log('Received plain text:', message);
} else if (message && message.message) {
// Handle JSON message (assuming message is in { message: string } format)
console.log('Received JSON message:', message);
} else {
console.log('Received unknown format:', message);
}
});
}
// Send a message to the WebSocket server
sendMessage(message: any) {
this.socket$.next(message);
}
getMessages() {
return this.socket$.asObservable();
}
// Close the WebSocket connection
closeConnection() {
this.socket$.complete();
}
}
sendFunction in chatcomponentts
// Send a message through WebSocket
sendMessage(): void {
console.log("user sender id : ",this.userSenderId);
const chatMessage = {
messageStatus:'UNSEEN',
senderId:this.userSenderId,
receiverId: this.ownerid,
message:this.message
}
this.chatService.sendMessageBetweenTwoUsers(chatMessage).subscribe((data)=>{
this.webSocketService.sendMessage(chatMessage.message);
this.chatData.push(data);
// this.getUserContacts(this.userSenderId);
this.getUserContactsWithCount(this.userSenderId);
})
if (this.message.trim()) {
console.log('Message Sent:', this.message);
const messagePayload = {
senderId: this.userSenderId, // Current user sender ID
receiverId: this.ownerid, // ID of the recipient
message: this.message.trim() // The message content
};
// Send the message to the WebSocket server
this.webSocketService.sendMessage(messagePayload);
this.message = ''; // Clear the message input field after sending
}
}
Upvotes: -4
Views: 23