I made a simple server app with Dart that receives and returns messages. It works great except when I stop the program the server keeps running in the background and I have to go to the cmd to kill the task before running the program again.
Why does the server not terminate when the program is stopped, and how do I fix that?
import 'dart:io' show HttpServer, HttpRequest, WebSocket, WebSocketTransformer;
void main() {
var sockets = <WebSocket>[];
var i = 0;
HttpServer.bind('localhost', 8080).then((HttpServer server) {
print('[+]WebSocket listening at -- ws://localhost:8080/');
server.listen((HttpRequest request) {
WebSocketTransformer.upgrade(request).then((WebSocket ws) {
sockets.add(ws);
ws.listen(
(data) {
print(data);
for(var socket in sockets) {
socket.add('a msg back from the server: $i');
}
i++;
},
onDone: () => print('[+]Done :)'),
onError: (err) => print('[!]Error -- ${err.toString()}'),
cancelOnError: true,
);
}, onError: (err) => print('[!]Error -- ${err.toString()}'));
}, onError: (err) => print('[!]Error -- ${err.toString()}'));
}, onError: (err) => print('[!]Error -- ${err.toString()}'));
}
Thanks in advance for the help.
Related
I created a service worker for a payment manager. When I checked the server is installed but I do not see the payment methods installed on the browser.
i added the event install fetch and load but i can't show the payment methods register in browser..
Any help please
My installer is
navigator.serviceWorker.register('sw.js').then(() => {
return navigator.serviceWorker.ready;
}).then((registration) => {
if (!registration.paymentManager) {
console.log('No payment handler capability in this browser. Is chrome://flags/#service-worker-payment-apps enabled?');
return;
}
if (!registration.paymentManager.instruments) {
return;
}
registration.paymentManager.instruments
.set('instrument-key', {
name: 'Chrome uses name and icon from the web app manifest',
enabledMethods: ['https://...'],
method: 'https://...',
})
.then(() => {
registration.paymentManager.instruments.get('instrument-key').then((instrument) => {
}).catch(...
})
My server worker
let payment_request_event;
let resolver;
let client;
const addResourcesToCache = async (resources) => {
const cache = await caches.open("v1");
await cache.addAll(resources);
};
self.addEventListener('install', event => {
event.waitUntil(
addResourcesToCache([
"/",
"/index.html",
])
);
console.log(`SW: Event fired: ${event.type}`);
console.dir(event);
});
self.addEventListener('activate', event => {
console.dir(event);
});
self.addEventListener('fetch', event => {
event.respondWith(fetch(event.request));
});
self.addEventListener('canmakepayment', e => {
console.log('canmakepayment', e);
e.respondWith(true);
});
self.addEventListener('paymentrequest', async e => {
console.log(e)
payment_request_event = e;
e.respondWith(resolver.promise);
// Open the checkout page.
try {
// Open the window and preserve the client
client = await e.openWindow('https://...html');
...
Our iOS app has audio video calling implemented using the following technologies:
"react-native": "0.63.4"
"react": "16.13.1"
"react-native-webrtc": "^1.87.3"
"react-native-incall-manager": "^3.3.0"
iOS version 14.4.1
Our calling module works like the following:
First request and initiate audio call
Then request and initiate video call
On the code side things work like this:
We call the getStream() function which gets the user media for audio call i.e Audio only
Then we call the startStream() function which connects the peer connection
On requesting video we call the getVideoStream() method to get Audio and Video streams
Call startStream() again to start peer connection with video
The scenario is as follows:
We start off by connecting an audio call. On success the audio call is connected and works fine as expected
We request for video and connect video call, all works fine as expected and I receive video on both ends
When I disconnect the call and stop tracks using this.state.localStream.getTracks(), the mic does not close. An orange indicator for mic is visible on iOS.
Important Notes:
Disconnecting from the audio call closes the mic just fine
Even if we get video stream on audio call and disconnect without connecting video it still works fine and closes both tracks
Its only when I connect the video is when the issue arises
Calling InCallManager.stop() closes the mic but does not open it on second call. The mic does not open on second call and the orange mic indicator on iOS is not shown.
Get User Media Audio Call
getStream() {
InCallManager.setSpeakerphoneOn(false);
InCallManager.setMicrophoneMute(false);
mediaDevices.enumerateDevices().then((sourceInfos) => {
let videoSourceId;
for (let i = 0; i < sourceInfos.length; i++) {
const sourceInfo = sourceInfos[i];
if (
sourceInfo.kind === 'videoinput' &&
sourceInfo.facing === (true ? 'front' : 'back')
) {
videoSourceId = sourceInfo.deviceId;
}
}
mediaDevices
.getUserMedia({
audio: true,
})
.then((stream) => {
this.setState({
localStream: stream,
});
})
.catch((error) => {
// Log error
console.log('stream get error', error);
});
});
}
Get User Media for Video Call
getVideoStream() {
this.state.peerConn.removeStream(this.state.localStream);
InCallManager.setSpeakerphoneOn(false);
InCallManager.setMicrophoneMute(false);
mediaDevices.enumerateDevices().then((sourceInfos) => {
let videoSourceId;
for (let i = 0; i < sourceInfos.length; i++) {
const sourceInfo = sourceInfos[i];
if (
sourceInfo.kind === 'videoinput' &&
sourceInfo.facing === (true ? 'front' : 'back')
) {
videoSourceId = sourceInfo.deviceId;
}
}
mediaDevices
.getUserMedia({
audio: true,
mirror: true,
video: {
mandatory: {
minWidth: 500,
minHeight: 300,
minFrameRate: 30,
},
facingMode: true ? 'user' : 'environment',
optional: videoSourceId ? [{sourceId: videoSourceId}] : [],
},
})
.then((stream) => {
this.setState(
{
localStream: stream,
},
() => {
this.startStream();
},
);
})
.catch((error) => {
// Log error
console.log('stream get error', error);
});
});
}
Start Stream Function
startStream() {
console.log('start Stream');
this.newPeerConnection();
setTimeout(() => {
this.state.peerConn
.createOffer()
.then((sessionDescription) =>
this.setLocalAndSendMessage(sessionDescription),
)
.catch((error) => this.defaultErrorCallback(error));
}, 3000);
}
newPeerConnection()
newPeerConnection() {
var peerConn = new RTCPeerConnection({
iceServers: turnServer,
});
peerConn.onicecandidate = (evt) => {
console.log(`OnIceCan`);
if (evt.candidate) {
this.state.connection.invoke(
'addIceCandidate',
parseInt(this.state.ticket.pkTicketId),
JSON.stringify({
type: 'candidate',
sdpMLineIndex: evt.candidate.sdpMLineIndex,
sdpMid: evt.candidate.sdpMid,
candidate: evt.candidate.candidate,
}),
);
}
};
peerConn.addStream(this.state.localStream);
peerConn.addEventListener(
'addstream',
(stream) => {
InCallManager.setForceSpeakerphoneOn(false);
this.setState({
isSpeakerEnabled: false,
});
this.setState({
remoteStream: stream,
showAudioCallTimer: true,
});
},
false,
);
this.setState(
{
peerConn,
});
}
Close Tracks
if (this.state.localStream) {
const tracks = this.state.localStream.getTracks();
tracks.map((track, index) => {
track.stop();
});
}
if (this.state.peerConn) {
this.state.peerConn.removeStream(this.state.localStream);
this.state.peerConn.close();
if (!this.state.callRatingSubmitted && this.state.remoteStream) {
this._handleCallFeedbackModal(true);
}
}
I am working on an Angular7 project and have some issues about error handling on http requests.
Here is my Login Component with two functions
export class LoginComponent implements OnInit, OnDestroy {
emailLogin1() {
this.authService.emailLogin1(this.loginForm.value).pipe(delay(1000)).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
emailLogin2() {
this.authService.emailLogin2(this.loginForm.value).pipe(delay(1000)).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
}
Here is my AuthService with two functions.
export class AuthService {
constructor(private http: HttpClient) {
}
emailLogin1(values): any {
return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
tap(
(response) => {
localStorage.setItem('token', response['token']);
},
(error) => {
console.log(error);
}
)
);
}
emailLogin2(values): any {
return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
tap(
(response) => {
localStorage.setItem('token', response['token']);
}
),
catchError((error) => {
console.log(error);
throw error;
})
);
}
}
When I make a request to the server, if response status is successful, it waits for 1000 ms and then shows the result as expected. But if response returns an error, delay(1000) function not working and error block working immediately. I tried with and without catchError. Both working exactly the same.
The delay operator will only work on events sent through the observable via "next" notifications (in your case, this is a "success"). When an error occurs, it is sent as an "error" notification, and it skips right past your delay operator. If you want to delay the error, you should catch it, introduce a delay, and then re-throw it:
emailLogin1() {
this.authService.emailLogin1(this.loginForm.value).pipe(
delay(1000), // only affects "success"
catchError(error => interval(1000).pipe( // only affects "error"
mergeMap(() => throwError(error)) // re-throw error after our delay
)),
).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
)
}
My app requires being connected to our server for any use. I wrote this function in the app component to prevent the user from using the app if the server is not available
app.component.ts
pingServer(){
this.api.pingServer().subscribe(result => {
if (result.success) {
return true;
}
else {
return false
}
},
error=>{
return false;
}
);
}
}
this function just makes the request to our server, which I verified is hitting the right address
initializeApp() {
console.log("initialize");
this.platform.ready().then(() => {
console.log("platform ready");
this.screenOrientation.lock('portrait');
console.log('Orientation is ' + this.screenOrientation.type);
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
let serverAlert = this.alertCtrl.create({
title: 'Error',
subTitle: 'We are unable to reach our servers at this time. Please try again later',
buttons: ['Dismiss']
});
setTimeout(() => {
if(this.pingServer){
console.log('pinged server successfully');
this.statusBar.styleDefault();
this.splashScreen.hide();
}
else{
console.log('unable to ping server');
return serverAlert.present();
}
}, 3000);
On the server side:
router.get( '/ping', ( req, res, next ) => {
return res.json( { success: true } );
} )
This worked fine when testing on the browser. However, when using iOS it says it pings successfully every time, meanwhile, the server isn't receiving the request.
On the simulator it does not crash and Alerts the error, but in production it is crashes as soon as fetch request suppose to be made and it is impossible to reopen the app until network connection is back (I turn on/off airplane mode for the testing)
here are the snippets of my code
componentWillMount: function(){
NetInfo.isConnected.addEventListener('change',this.handleConnectivityChange)
NetInfo.isConnected.fetch().done((data) => {
this.setState({
isConnected: data
})
console.log('this.state.isConnected: ', this.state.isConnected);
})
},
handleConnectivityChange: function(){
var connected = this.state.isConnected ? false : true
this.setState({isConnected: connected})
console.log('this.state.isConnected11: ', this.state.isConnected);
},
....
goToList: function(replace, listview){
console.log('this.state.isConnected: ', this.props.isConnected);
if (!this.props.isConnected){
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
return
}
....
fetch(url)
.then((response) => response.json())
.then((responseData) => {
....
.catch((error) => {
StatusBarIOS.setNetworkActivityIndicatorVisible(false)
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
})
.done()
I spent a lot of time trying to find a way to catch exceptions when using fetch() but I was unable to get it working (e.g. using .catch() or a try/catch blog didn't work). What did work was to use XMLHttpRequest with a try/catch blog instead of fetch(). Here's an example I based off of: https://facebook.github.io/react-native/docs/network.html#using-other-networking-libraries
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
var responseJson = JSON.parse(request.responseText);
// *use responseJson here*
} else {
console.warn('error');
}
};
try {
request.open('GET', 'https://www.example.org/api/something');
request.send();
} catch (error) {
console.error(error);
}