I want to store the variable X in a file/DB in server side. Client side is written using AngularJS and server side is using JAVA. The Connection is established using WebSocket.
Now whenever the connection is closing(both when I close it manually and when it closes automatically on some error), I have to send the variable X from AngularJs to JAVA. What is the good way to do that?
Connection establishment - AngularJS code
angular.module('main')
.factory('socket', function ($websocket,$cookies,$state) {
// Open a WebSocket connection
var ws = $websocket("ws://" + document.location.host + "/Server/dialog");
var X = [];
ws.onMessage(function (event) {
console.log('message: ', event.data);
var response;
response = event.data;
X.push({
//some data
});
});
ws.onError(function (event) {
console.log('connection Error', event);
});
ws.onClose(function (event) {
console.log('connection closed', event);
X.push({
//some closing msg
});
//From here I have to send the variable X to the server side
});
ws.onOpen(function () {
console.log('connection open');
ws.send("HELLO");
});
return {
X: X,
status: function () {
return ws.readyState;
},
send: function (message) {
if(message != null){
console.log(message);
X.push({
//some data
});
ws.send(message);
}
}
};
})
How to send the variable while connection is closing?
Related
I'm building a react application that uses atmosphere library to listen to a SpringBoot websocket, when the client tries to connect to the server, it throws an error in the console saying Some cookies are misusing the recommended “sameSite“ attribute. I added some attributes to the request object to fix the issue as recommended (SameSite cookies). but I'm still getting the same error.
ReactJS code:
import React from 'react';
import * as atmosphere from 'atmosphere.js';
//import $ from 'jquery';
var transport = 'websocket';
//var req = new atmosphere.AtmosphereRequest();
// We are now ready to cut the request
var request = {
url:'http://localhost:8080/stream',
contentType: "application/json",
trackMessageLength: true,
shared: true,
enableXDR: true,
headers: { 'Access-Control-Allow-Origin': '*',
'sameSite': ' None; Secure'
},
//sameSite: 'None; Secure',
rewriteURL:true,
transport: transport,
fallbackTransport: 'long-polling',
onOpen: function(response:any) {
console.log('Atmosphere connected using ' , response.transport);
transport = response.transport;
},
onTransportFailure: function(errorMsg: Atmosphere.Response, request: Atmosphere.Request) {
console.log('Atmosphere Chat. Default transport is WebSocket, fallback is ' ,request.fallbackTransport );
},
onMessage: function (response:Atmosphere.Response) {
var message = response.responseBody;
try {
console.log('message: ', message);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message);
return;
}
},
onClose : function(response: Atmosphere.Response) {
console.log("Close connection !!!");
}
};
const socket = atmosphere;
// Connect to the server, hook up to the request handler.
console.log('socket : ', socket.subscribe);
socket.subscribe && socket.subscribe(request);
const AtmosphereWebSocket = () => {
return ( <div> </div> );
}
export default AtmosphereWebSocket;
SpringBoot Code:
#Component
#CrossOrigin(origins = "http://localhost:3000")
#WebSocketHandlerService(path = "/stream", broadcaster = SimpleBroadcaster.class,
atmosphereConfig = {"org.atmosphere.websocket.WebSocketProtocol=" +
"org.atmosphere.websocket.protocol.StreamingHttpProtocol"})
public class WebSocketStream extends WebSocketStreamingHandlerAdapter {
private final Logger logger = LoggerFactory.getLogger(WebSocketStream.class);
public WebSocketStream() {
System.out.println(" ** WebSocketStream ** ");
}
// A thread which sends a stream of data out of a websocket. Create when the class
// is instantiated, inject the websocket when open.
private class Stream extends Thread {
protected WebSocket socket;
protected final ObjectMapper mapper = new ObjectMapper();
protected boolean stop = false;
public Stream(WebSocket socket) {
this.socket = socket;
}
public void run() {
int count = 0;
try {
while (!stop) {
Map<String, Object> message = new HashMap<String, Object>();
message.put("time", new Date().toString());
message.put("count", count++);
String string = mapper.writeValueAsString(message);
socket.write(string);
System.out.println("tick: " + string);
Thread.sleep(1000);
}
} catch (Exception x) {
// break.
}
}
}
int clients = 0;
#Override
public void onOpen(WebSocket webSocket) throws IOException {
// Hook up the stream.
final Stream stream = new Stream(webSocket);
stream.start();
logger.info(" on open was called !!!");
webSocket.broadcast("client " + clients++ + " connected");
webSocket.resource().addEventListener(new WebSocketEventListenerAdapter() {
#Override
public void onDisconnect(AtmosphereResourceEvent event) {
if (event.isCancelled()) {
logger.info("Browser {} unexpectedly disconnected", event.getResource().uuid());
} else if (event.isClosedByClient()) {
logger.info("Browser {} closed the connection", event.getResource().uuid());
}
stream.stop = true;
}
});
}
}
Error Message:
Websocket failed on first connection attempt. Downgrading to long- polling and resending 1.chunk.js:3632:18
Atmosphere Chat. Default transport is WebSocket, fallback is long-polling atmosphere.tsx:27
The development server has disconnected.
Refresh the page if necessary. 1.chunk.js:7419:13
Sat Jul 11 2020 15:52:07 GMT-0500 (Central Daylight Time) Atmosphere: unload event 1.chunk.js:3632:18
[HMR] Waiting for update signal from WDS... log.js:24
Download the React DevTools for a better development experience: react-dom.development.js:24994
socket :
function subscribe(url, callback, request)
atmosphere.tsx:47
Firefox can’t establish a connection to the server at ws://localhost:8080/stream?X-Atmosphere-tracking-id=0&X-Atmosphere-Framework=3.0.5-javascript&X-Atmosphere-Transport=websocket&X-Atmosphere-TrackMessageSize=true&Content-Type=application/json&X-atmo-protocol=true&Access-Control-Allow-Origin=*&sameSite=%20None%3B%20Secure. atmosphere.js:1201
Websocket closed, reason: Connection was closed abnormally (that is, with no close frame being sent). - wasClean: false atmosphere.js:3302
Close connection !!! atmosphere.tsx:40
Websocket failed on first connection attempt. Downgrading to long-polling and resending atmosphere.js:3302
Atmosphere Chat. Default transport is WebSocket, fallback is long-polling
I want to send pdf file from server and display it in client side. I'm using server side technology as java and client side as angular 6. Please suggest me. Thanks in advance.
Using arraybuffer
service call:
In File Service:
getFileFromServer(url){
return this.httpService.getUploadedFile(url);
}
In HTTP service:
getUploadedFile(url:string){
//just for authentication and file access.
let headers = new HttpHeaders().append("Authorization", "Bearer " + token)
return this.httpClient.get(url, {responseType: 'arraybuffer',headers:headers});
}
in component:
Using Blob
Blob reference -----> Blob
Here this.type = 'application/pdf'
For Example User Clicks on View Button:
than (click)="getPdfFile()" will fire.
It will call service method to get response as arraybuffer
getPdfFile() {
this.fileService.getFileFromServer(url).subscribe(responseData => {
//catch response as array buffer
this.showPdfFile(responseData, this.type);
}, error => {
//catch error if any
console.log(error);
});
}
showPdfFile(data: any, type: string) {
var blob = new Blob([data], { type: type });
var url = window.URL.createObjectURL(blob);
// it will open url to new tab.
window.open(url);
}
I have Play Framework(2.1) Web application. I need to send large data info from the client side to Controller. For this purpose I use ajax:
Client side :
$.ajax({
type : 'POST',
url : '#routes.SomeController.saveInfo()',
data : {
myJson: "LargeData"
},
success : function(data) {
alert("Ok")
},
error: function() {
alert("Error!")
}
});
return false;
}
Server side:
POST /saveInfo controllers.SomeController.saveInfo()
public static Result saveInfo() {
request().body().asFormUrlEncoded(); // NULL
request().body().asJson(); // NULL
request().body().asMultipartFormData(); // NULL
request().body().asText(); //NULL
request().body().asXml(); //NULL
return ok();
}
By that way I can send small portion of data but not large. Where is the mistake? Or How I can send large data from client to server side?
I have the following getJSON request:
$.getJSON(url + "&callback=?", {
postData: myText
}, function(data) {
alert('data : ' + data);
});
For my testing I have an applicatoin running on "localhost:8080" and I am performing this getJSON from here in a JSP, and an HTTP Server running on "localhost:8090".
The URL I am using in my getJSON above, is the URL of this HTTP Server, i.e. "http://localhost:8090/json". This is available. On this URL, I am outputting a JSON based string.
So.. in my getJSON, I want to get this data back from what is being displayed on the HTTP Server page.
But it doesn't work.
This is my HTTP Server code:
public void RunHttpServerStart() {
HttpServer server = null;
try
{
HttpJsonHandler handler = new HttpJsonHandler();
server = HttpServer.create(new InetSocketAddress(8090), 10);
server.createContext("/json", handler); // The handler holds my JSON string being output
server.setExecutor(null); // creates a default executor
server.start();
System.out.println("Server is started");
while(handler.shutdown == false) { Thread.sleep(1000); }
System.out.println("Stopping server");
}
catch(Exception ex) { System.out.println(ex.getMessage());}
finally {
if(server != null)
server.stop(0);
}
}
I have implemented the example from JQUERY's website for getJSON with the images from flicker, but how do I get this string data back in the getJSON call?
Try using regular $.get with a jsonp datatype.
$.get(url, {
postData: myText
}, function(data) {
alert('data : ' + data);
}, 'jsonp');
Im trying to use the Channel API of Google App Engine.
JavaScript / JQuery:
$(document).ready(function(){
alert('ready');
$.post('/token', function(data) {
alert('token:' + data['token']);
openChannel( data['token'] );
});
$.post('/chat', function(data) {
alert('chat:' + data['users'].length);
});
});
onMessage = function(message) {
alert(message);
}
onSocketError = function(error){
alert("Error is <br/>"+error.description+" <br /> and HTML code"+error.code);
};
onSocketOpen = function() {
// socket opened
};
onSocketClose = function() {
alert("Socket Connection closed");
};
openChannel = function(token) {
alert('open channel');
var channel = new goog.appengine.Channel( token );
var socket = channel.open();
socket.onopen = onSocketOpen;
socket.onmessage = onMessage;
socket.onerror = onSocketError;
socket.onclose = onSocketClose;
};
The problem is that alert(message) doesn't fire. What is lucking in my code?
Im confused on some of the examples having "\\{\\{ token \\}\\}" in server side and channel = new goog.appengine.Channel('{{ token }}') in javascript.
What is it enclosed in {{ }}?
Please note token is a TOKEN KEY which identifies your page. Initialize token in page first like:
ChannelService channelService = ChannelServiceFactory.getChannelService();
String token = channelService.createChannel("sample");
Now
var token ="<%=token %>";// This will creaete unique identifier(some id created by google api + ur key)
channel = new goog.appengine.Channel('<%=token%>');
socket = channel.open();
socket.onopen = function () {
var connected = true;
sendMessage('<b>'+userName+'</b> Logged in.');
};
.. Create functions like this
Besides using the correct token, your onMessage function doesn't fire because that will happen when you send a message from the server to the client:
channelService.sendMessage(new ChannelMessage(channelKey, "Hello World"));
you can set up a XMLHttpRequest in order to communicate from the client to the server side, where the java code before can be run, for example:
sendMessage = function(path, param) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'path + '&' + param', true);
xhr.send();
};
in javascript
function onMessage(msg)
{
var msg1=msg.data;
$('textarea').val($('textarea').val()+msg1);
}
in backend
ChannelService channelService = ChannelServiceFactory.getChannelService();
channelService.sendMessage(new ChannelMessage(clientid,message));