logo
down
shadow

SseEmitter with proxy


SseEmitter with proxy

By : Abraham Grijalva
Date : October 23 2020, 08:10 AM
wish help you to fix your issue Which proxy do you use? Some proxies need special configurations (content-length, headers, etc.) to support SSE and some don't (like the AWS load balancer (at least last year)).
code :


Share : facebook icon twitter icon
Spring rest service with SseEmitter

Spring rest service with SseEmitter


By : Yufeng Chang
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I think you are almost there, Allinone51.
Your call to SseEmitter.send() should probably be in the getUser method. The general pattern is that when you create the SseEmitter you need to "store" it somewhere for other code to get hold of it. You correctly return the SseEmitter from the getSseEmitter method, you just forgot to store it for the other method to be able to call 'send' on it.
code :
//...
private SseEmitter emitter;

@RequestMapping(value = "/{imei}", method = RequestMethod.GET)
public User getUser(@PathVariable String imei) { 
    User myUser = null;

    // .. do resolving of myUser (e.g. database etc).

    // Send message to "connected" web page:
    if (emitter != null) {
        emitter.send(myUser.toString()); // Or format otherwise, e.g. JSON.
    }

    // This return value goes back as a response to your android device
    // i.e. the caller of the getUser rest service.
    return myUser;
}

@RequestMapping(value = "/sse")
public SseEmitter getSseEmitter() {
    emitter = new SseEmitter();
    return emitter;
}
Spring SseEmitter over WebSocket connection

Spring SseEmitter over WebSocket connection


By : SKB
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Here is an example of both WebSocket and SSE. As noted above SSE is not supported by IE browsers. Adding as much as I can for completeness. Make sure you are not using a RestController when you use SeeEmitter because that will return the object and that is my guess from the description above.
pom.xml
code :
<dependencies>
    <!-- Spring boot framework -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
</dependencies>
@Configuration
@EnableWebSocketMessageBroker
public class ApplicationWebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        super.configureMessageBroker(registry);
        registry.enableSimpleBroker("/topic");
    }

    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry.addEndpoint("/socketrequest").withSockJS();
    }
}
public class RequestData {
    private String string1;
    private String string2;
    // excluding getters and setters
}
@Controller
public class WebSocketController {
   @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/processrequest")
    void runWebSocket( RequestData requestData ) {
        new Thread(new RunProcess(requestData)).start();
    }

    private class RunProcess implements Runnable {
        private RequestData requestData;

        RunProcess(RequestData requestData) {
            this.requestData = requestData;
        }

        public void run() {
            simpMessagingTemplate.convertAndSend("/topic/response", requestData.getString1());
            simpMessagingTemplate.convertAndSend("/topic/response", requestData.getString2());
            simpMessagingTemplate.convertAndSend("/topic/response", "A third response via websocket");
        }
    }
}
@Controller
public class SseController {

    @RequestMapping("/emitter")
    public SseEmitter runEmitter(@RequestParam(value = "string1") String string1,
                                 @RequestParam(value = "string2") String string2)
    {
        SseEmitter sseEmitter = new SseEmitter();
        RequestData requestData = new RequestData();
        requestData.setString1(string1);
        requestData.setString2(string2);
        new Thread(new RunProcess(requestData,sseEmitter)).start();
        return sseEmitter;
    }

    private class RunProcess implements Runnable {
        private RequestData requestData;
        private SseEmitter sseEmitter;

        RunProcess(RequestData requestData, SseEmitter sseEmitter) {
            this.requestData = requestData;
            this.sseEmitter = sseEmitter;
        }

        public void run() {
            try {
                sseEmitter.send(requestData.getString1());
                sseEmitter.send(requestData.getString2());
                sseEmitter.send("A third response from SseEmitter");
                sseEmitter.complete();
            } catch (IOException e) {
                e.printStackTrace();
                sseEmitter.completeWithError(e);
            }
        }
    }

}
    <script src="/javascript/sockjs-0.3.4.js"></script>
    <script src="/javascript/stomp.js"></script>

    <script type="text/javascript">
    var stompClient = null;

    function connect() {
        var socket = new SockJS('http://localhost:8085/socketrequest');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/response', function(message){
                showOutput(message.body);
            });
        });
    }

    function doWebsocket() {
        stompClient.send("/processrequest", {}, JSON.stringify({ 'string1': 'The first string', 'string2' : 'The second string' }));
    }


    function doSse() {
        console.log("doSse");
        var rtUrl= '/emitter?string1=first string sse&string2=second string sse';
        var source = new EventSource(rtUrl);
        source.onmessage=function(event){
            showOutput(event.data)
        };
    }

    function showOutput(message) {
        var response = document.getElementById('response');
        var p = document.createElement('p');
        p.style.wordWrap = 'break-word';
        p.appendChild(document.createTextNode(message));
        response.appendChild(p);
    }

    connect();

    </script>
    </head>

<div>
Starting page
</div>
<div>
    <button id="websocket" onclick="doWebsocket();">WebSocket</button>
    <button id="sse" onclick="doSse();">Server Side Events</button>
</div>
<div >
    Response:
    <p id="response"></p>
</div>

</html>
How to avoid HttpMediaTypeNotAcceptableException with Spring SseEmitter on timeout

How to avoid HttpMediaTypeNotAcceptableException with Spring SseEmitter on timeout


By : William Porquet
Date : March 29 2020, 07:55 AM
wish help you to fix your issue The error was not on the server side. After clicking around on the client a couple of times, there were suddenly two client side EventSource objects. This is what caused the errors.
Media Type not acceptable exception when using SseEmitter

Media Type not acceptable exception when using SseEmitter


By : cc__
Date : March 29 2020, 07:55 AM
help you fix your problem I Was in the middle of doing something else when I got the same issue. The code below fixed it.
Simply put Mismatch Media type.
code :
@GetMapping(value = "/api/push/notification",headers = "Accept=*/*", consumes = MediaType.ALL_VALUE, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public String doNotify(@RequestParam("authToken") String token, @RequestParam("clientId") String clientId, HttpServletResponse response) throws InterruptedException, IOException {
    response.addHeader("charset","UTF-8");
    final SseEmitter emitter = new SseEmitter(30000l);
        service.addEmitter(clientId,emitter);
        service.sendConnectedNotification(clientId);
        emitter.onCompletion(() -> service.removeEmitter(clientId));
        emitter.onTimeout(() -> service.removeEmitter(clientId));
    return "Connected OK";
}
 @Async
public void doNotify(String clientId, Object data) {
    SseEmitter emitter= emitters.get(clientId);
    if(emitter!=null) {
        try {
            emitter .send(SseEmitter.event() .reconnectTime(30000)
                .data(data,MediaType.APPLICATION_JSON)
                .id(UUID.randomUUID().toString())
                .name("Notification")
                .comment("Client connection notification")
            );
        } catch (Exception e) {
            emitters.remove(clientId);
        }
    }
}
Spring SSEEmitter Getting Completed Mid-way

Spring SSEEmitter Getting Completed Mid-way


By : Mehreen
Date : March 29 2020, 07:55 AM
may help you . Your builder is not being used; you create and configure a builder, but then you send a plain message with 'sseEmitter.send' directly. Try this:
Related Posts Related Posts :
  • SpringBoot : No matching bean found exception
  • Implementing the Clonable interface, but don't have to override the clone() method
  • how can i get this code to choose a random word once from each array to print a sentence?
  • Static class to get connections from connection pool
  • Unable to start Chrome browser with user profile in Selenium
  • How to pass a object to be created as a parameter for a method in Java?
  • How to retry with hystrix
  • Loading key to KeyStore fails on Android Oreo
  • Spring+Velocity unsuccessful attempts to save object
  • Private constructor in Kotlin
  • Jetty:run fails with NoSuchMethodError with Spring 5
  • Cannot upload my Web Applicartion in Jboss7 EAP7 EAP
  • How to load a certificate from "Credential storage"?
  • Call Genexus procedure stub in Java environment
  • JavaFX clipping produces a 'lottery scratch ticket'-Effect
  • Using DateTimeFormatter on january first cause an invalid year value
  • Get all the output from Watson conversation using java
  • Java unable to open main class and jar file
  • How to override @override method from activity into another class
  • Adding Runtime VM parameters to intellij for Java 9
  • Java IBM MQ Client connected but not getting messages from queue
  • Questions of Tomcat SSL configuration
  • Stale JNLP files for <extension> (since Java 9?)
  • Properly set (system) properties in JUnit 5
  • Spring MVC Model within POST Method is empty
  • VSTS buildagent: Java 9
  • java.lang.NumberFormatException: For input string: "id" for Hibernate
  • Query id return type
  • Pass variable in API url in java .
  • Reading semicolon delimited csv
  • Get the workspace root
  • Native mmap error
  • hashmap and multiple txt files java
  • Kotlin: Access nested enum class from java
  • Google RateLimiter not Working for counter
  • Spring Boot Application Hanging When Running on Command Line
  • large amount of if else refactor
  • Unable to add xmlunit as dependancy in my pom
  • Scanner input needed twice, when only wanted once
  • How to interpret and translate kotlin code to java?
  • Firebase authentication: signInWithEmailAndPassword method dont respond at all
  • How Remove Recycler Separator/divider programmatically or using xml property
  • Not Able to Save Data Hibernate
  • Toolbar addView not working
  • Freeing memory wrapped with NewDirectByteBuffer
  • Synchronization with implicitwait() do not work, why?
  • Wrapper around Java primitive types
  • ClassNotFoundException: spark.Request when running from command line
  • Exception in Hibernate Configuration
  • How can I validate XML embedded in JSON using Citrus framework?
  • How is the String value passed to the updateText() method?
  • Memory efficient replace functions
  • Upload Photo with onActivityResult, but without Fullscreen capturing
  • Docker: Java 8 installation failing on Ubuntu
  • Java Netbeans Calculator performing wrong calculation
  • Nifi: Threads in nifi
  • While loop Int return inside the method completely dead
  • Checking if a user's entry is an integer using try catch statements
  • Forcing a subclass to provide an initialization method
  • calling a fuction and variables from another class in java
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org