Skip to content

Commit

Permalink
basic chat with sockets.io [skip ci]
Browse files Browse the repository at this point in the history
  • Loading branch information
ylivuoto committed Feb 14, 2025
1 parent 4c03588 commit 14b2a74
Show file tree
Hide file tree
Showing 6 changed files with 349 additions and 54 deletions.
42 changes: 32 additions & 10 deletions timApp/events/websocket.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {Injectable} from "@angular/core";
import type {WebSocketSubject} from "rxjs/webSocket";
import {webSocket} from "rxjs/webSocket";
import type {Observable} from "rxjs";
// import type {WebSocketSubject} from "rxjs/webSocket";
// import {webSocket} from "rxjs/webSocket";
import type {Socket} from "socket.io-client";
import {io} from "socket.io-client";

interface IMessage {
type: string;
Expand All @@ -12,24 +13,45 @@ interface IMessage {
providedIn: "root",
})
export class WebSocketService {
private socket$: WebSocketSubject<IMessage>;
// private socket: WebSocketSubject<string>;
private socket: Socket;
messages$: IMessage[] = [];

constructor() {
this.socket$ = webSocket("ws://localhost:443/chat");
// this.socket = webSocket("ws://localhost/");
this.socket = io("http://localhost", {
transports: ["websocket"],
});
this.socket.on("message", (data: IMessage) => {
console.log(data);
this.messages$.push(data);
});
}

// Send a message to the server
sendMessage(message: IMessage) {
this.socket$.next(message);
console.log("Send happened: ", message);
this.socket.send(message);
// this.messages$.push(message);
// this.socket.next(JSON.stringify(message));
}

listenSocket() {}

// Receive messages from the server
getMessages(): Observable<IMessage> {
return this.socket$.asObservable();
}
/* listenSocket(): void {
console.log("Listening...");
this.socket.subscribe({
next: (msg) => this.messages$.push(msg), // Called whenever there is a message from the server.
error: (err) => console.log(err), // Called if at any point WebSocket API signals some kind of error.
complete: () => console.log("complete"), // Called when connection is closed (for whatever reason).
});
console.log("Messages: ", this.messages$);
}*/

// Close the WebSocket connection
closeConnection() {
this.socket$.complete();
this.socket.off();
// this.socket.complete();
}
}
237 changes: 227 additions & 10 deletions timApp/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 14b2a74

Please sign in to comment.