improve socket

This commit is contained in:
Peter Maquiran
2024-01-31 17:12:01 +01:00
parent 76b0046a22
commit 793c861cbf
9 changed files with 758 additions and 671 deletions
+139 -143
View File
@@ -10,60 +10,60 @@ import { HubConnectionBuilder } from '@microsoft/signalr';
providedIn: 'root'
})
export class SocketConnectionMCRService {
private callbacks: Function[] = []
private onDisconnect: Function[] = []
private onConnect: Function[] = []
// private callbacks: Function[] = []
// private onDisconnect: Function[] = []
// private onConnect: Function[] = []
constructor(private http: HttpClient,) {
window["http"] = this.http
}
// constructor(private http: HttpClient,) {
// window["http"] = this.http
// }
connect() {
// connect() {
var connection = new signalR.HubConnectionBuilder()
.withUrl("https://gdcmapi-dev.dyndns.info/FileHub", {
accessTokenFactory: () => "Bearer "+SessionStore.user.Authorization
}).configureLogging(signalR.LogLevel.Information)
.build();
// var connection = new signalR.HubConnectionBuilder()
// .withUrl("https://gdcmapi-dev.dyndns.info/FileHub", {
// accessTokenFactory: () => "Bearer "+SessionStore.user.Authorization
// }).configureLogging(signalR.LogLevel.Information)
// .build();
connection.on("ReceiveMessage", (message) => {
console.log("ReceiveMessage", message)
})
// connection.on("ReceiveMessage", (message) => {
// console.log("ReceiveMessage", message)
// })
connection.onreconnected((connectionId) => {
console.assert(connection.state === signalR.HubConnectionState.Connected);
console.log(`Reconnected with connectionId: ${connectionId}`);
});
// connection.onreconnected((connectionId) => {
// console.assert(connection.state === signalR.HubConnectionState.Connected);
// console.log(`Reconnected with connectionId: ${connectionId}`);
// });
connection.start()
.then(() => {
console.log("SignalR connection started.");
})
.catch((error) => {
console.error("Error starting SignalR connection:", error);
});
// connection.start()
// .then(() => {
// console.log("SignalR connection started.");
// })
// .catch((error) => {
// console.error("Error starting SignalR connection:", error);
// });
connection.onclose((error) => {
connection.start()
console.log("SignalR connection closed:", error);
});
// connection.onclose((error) => {
// connection.start()
// console.log("SignalR connection closed:", error);
// });
}
// }
subscribe(callback) {
this.callbacks.push(callback);
}
// subscribe(callback) {
// this.callbacks.push(callback);
// }
unsubscribe(callback) {
this.callbacks = this.callbacks.filter(cb => cb !== callback);
}
// unsubscribe(callback) {
// this.callbacks = this.callbacks.filter(cb => cb !== callback);
// }
onDisconnectCallback(callback) {
this.onDisconnect.push(callback)
}
onConnectCallback(callback) {
this.onConnect.push(callback)
}
// onDisconnectCallback(callback) {
// this.onDisconnect.push(callback)
// }
// onConnectCallback(callback) {
// this.onConnect.push(callback)
// }
}
@@ -74,6 +74,7 @@ class ReconnectingWebSocketSignalR {
private callbacks: Function[] = []
private onDisconnect: Function[] = []
private onConnect: Function[] = []
private stop = true
constructor() {
this.isOpen = false;
@@ -81,9 +82,13 @@ class ReconnectingWebSocketSignalR {
}
connect() {
console.log("try to connect=================================")
this.stop = false
this.connection = new signalR.HubConnectionBuilder()
.withUrl("https://gdcmapi-dev.dyndns.info/FileHub", {
accessTokenFactory: () => "Bearer "+SessionStore.user.Authorization
transport: signalR.HttpTransportType.LongPolling,
accessTokenFactory: () => SessionStore.user.Authorization
}).configureLogging(signalR.LogLevel.Information)
.build();
@@ -95,16 +100,15 @@ class ReconnectingWebSocketSignalR {
this.onConnect.forEach(callback => callback());
console.log("SignalR connection started.");
})
.catch((error) => {
console.error("Error starting SignalR connection:", error);
console.error("Error starting SignalR connection:", error);
});
this.connection.on("ReceiveMessage", (message) => {
const data: any = JSON.parse(message)
console.log(data)
console.log("ReceiveMessage", data)
this.callbacks.forEach(callback => callback(data));
})
@@ -113,12 +117,27 @@ class ReconnectingWebSocketSignalR {
this.isOpen = false;
this.onDisconnect.forEach(callback => callback());
// Attempt to reconnect after a delay
setTimeout(() => {
this.connect();
}, 1000); // Adjust the delay as needed
if(this.stop) {
setTimeout(() => {
this.connect();
}, 1000); // Adjust the delay as needed
}
});
}
disconnect() {
this.stop = true
this.connection.stop()
.then(() => {
console.log('WebSocket connection closed');
this.isOpen = false;
this.onDisconnect.forEach(callback => callback());
console.log("SignalR connection stopped.");
})
.catch((error) => {
console.error("Error stopping SignalR connection:", error);
});
}
subscribe(callback) {
@@ -143,81 +162,81 @@ interface socketResponse {
Guid: string
isCompleted: Boolean
}
class ReconnectingWebSocket {
// class ReconnectingWebSocket {
private url: string
private socket
isOpen: boolean
private callbacks: Function[] = []
private onDisconnect: Function[] = []
private onConnect: Function[] = []
// private url: string
// private socket
// isOpen: boolean
// private callbacks: Function[] = []
// private onDisconnect: Function[] = []
// private onConnect: Function[] = []
http: HttpClient = window["http"]
// http: HttpClient = window["http"]
constructor(url) {
this.url = url;
this.socket = null;
this.isOpen = false;
this.connect();
}
// constructor(url) {
// this.url = url;
// this.socket = null;
// this.isOpen = false;
// this.connect();
// }
connect() {
this.socket = new WebSocket(this.url);
// connect() {
// this.socket = new WebSocket(this.url);
this.socket.addEventListener('open', (event) => {
this.isOpen = true;
console.log('WebSocket connection established');
// this.socket.addEventListener('open', (event) => {
// this.isOpen = true;
// console.log('WebSocket connection established');
// Example: Send a message to the server
this.socket.send('Hello, WebSocket Server!');
this.onConnect.forEach(callback => callback());
});
// // Example: Send a message to the server
// this.socket.send('Hello, WebSocket Server!');
// this.onConnect.forEach(callback => callback());
// });
this.socket.addEventListener('message', (event) => {
const data: socketResponse = JSON.parse(event.data)
this.callbacks.forEach(callback => callback(data));
});
// this.socket.addEventListener('message', (event) => {
// const data: socketResponse = JSON.parse(event.data)
// this.callbacks.forEach(callback => callback(data));
// });
this.socket.addEventListener('close', (event) => {
console.log('WebSocket connection closed');
this.isOpen = false;
this.onDisconnect.forEach(callback => callback());
// Attempt to reconnect after a delay
setTimeout(() => {
this.connect();
}, 1000); // Adjust the delay as needed
});
}
// this.socket.addEventListener('close', (event) => {
// console.log('WebSocket connection closed');
// this.isOpen = false;
// this.onDisconnect.forEach(callback => callback());
// // Attempt to reconnect after a delay
// setTimeout(() => {
// this.connect();
// }, 1000); // Adjust the delay as needed
// });
// }
send(message) {
if (this.isOpen) {
this.socket.send(message);
} else {
console.error('WebSocket connection is not open. Unable to send message.');
}
}
// send(message) {
// if (this.isOpen) {
// this.socket.send(message);
// } else {
// console.error('WebSocket connection is not open. Unable to send message.');
// }
// }
close() {
if (this.isOpen) {
this.socket.close();
}
}
// close() {
// if (this.isOpen) {
// this.socket.close();
// }
// }
subscribe(callback) {
this.callbacks.push(callback);
}
// subscribe(callback) {
// this.callbacks.push(callback);
// }
unsubscribe(callback) {
this.callbacks = this.callbacks.filter(cb => cb !== callback);
}
// unsubscribe(callback) {
// this.callbacks = this.callbacks.filter(cb => cb !== callback);
// }
onDisconnectCallback(callback) {
this.onDisconnect.push(callback)
}
onConnectCallback(callback) {
this.onConnect.push(callback)
}
}
// onDisconnectCallback(callback) {
// this.onDisconnect.push(callback)
// }
// onConnectCallback(callback) {
// this.onConnect.push(callback)
// }
// }
// export class ObjectMergeNotification{
@@ -293,9 +312,11 @@ export class ObjectMergeNotification{
this.socket.onConnectCallback(()=> {
this.runWatch = false
})
this.socket.subscribe((data: socketResponse) => {
if(data.isCompleted == true) {
console.log("==================!!!====================")
this.callbacks[data.Guid](data)
delete this.callbacks[data.Guid]
}
@@ -305,36 +326,9 @@ export class ObjectMergeNotification{
}
connect() {
var connection = new signalR.HubConnectionBuilder()
.withUrl("https://gdcmapi-dev.dyndns.info/FileHub", {
accessTokenFactory: () => "Bearer "+SessionStore.user.Authorization
}).configureLogging(signalR.LogLevel.Information)
.build();
connection.on("ReceiveMessage", (message) => {
console.log("ReceiveMessage", message)
})
connection.onreconnected((connectionId) => {
console.assert(connection.state === signalR.HubConnectionState.Connected);
console.log(`Reconnected with connectionId: ${connectionId}`);
});
connection.start()
.then(() => {
console.log("SignalR connection started.");
})
.catch((error) => {
console.error("Error starting SignalR connection:", error);
});
connection.onclose((error) => {
connection.start()
console.log("SignalR connection closed:", error);
});
close() {
console.log("close=============================================")
this.socket.disconnect();
}
async watch() {
@@ -354,6 +348,8 @@ export class ObjectMergeNotification{
}, 1000)
} else {
console.log("end loop============================")
}
}