14

I have a few problems with using websockets:

  • java.io.IOException: Broken Pipe
  • Client doesn't receive messages
    TL;DR

Main things I want to know:

  • Please list all possible scenarios why the client side closes the connection (apart from refreshing or closing the tab).
  • Can a Broken Pipe Exception occur, apart from the server sending a message to the client over a broken connection? If yes, then how?
  • What are the possible scenarios why a server doesn't send a message, although the server does send heartbeats? (When this happens, I need to restart the application for it to work again. This is a terrible solution, because it already is in production.)


I have a SpringMVC project that uses websockets; SockJS client side and org.springframework.web.socket.handler.TextWebSocketHandler server side.

A JSON is generated server side and send to the client. Sometimes, I get a java.io.IOException: Broken Pipe. I googled/StackOverflowed a lot and found too many things I don't understand, but the reason is probably the connection is closed client side and the server still sends a message (for example, a heartbeat). Does this sound okay? What are other causes for this exception to arise? What are the reasons for the client side to close the connection (apart from refreshing or closing the tab)?

Also, sometimes the client side doesn't get any messages from the server, although the server should send them. I log before and after sending the message, and both log statements are printed. Does anyone has an idea why this can occur? I have no errors in the console log of Chrome. Refreshing the page doesn't work, I need to restart the spring project...

If you need more info, please leave a comment.


Client side

function connect() {
    var socket = new SockJS('/ws/foo');

    socket.onopen = function () {
        socket.send(fooId); // ask server for Foo with id fooId.
    };

    socket.onmessage = function (e) {
        var foo = JSON.parse(e.data);
        // Do something with foo.
    };
}

Server side
Service

@Service
public class FooService implements InitializingBean {
    public void updateFoo(...) {
        // Update some fields of Foo.
        ...
        // Send foo to clients.
        FooUpdatesHandler.sendFooToSubscribers(foo);
    }
}

WebSocketHandler

public class FooUpdatesHandler extends ConcurrentTextWebSocketHandler {
// ConcurrentTextWebSocketHandler taken from https://github.com/RWTH-i5-IDSG/BikeMan (Apache License version 2.0)

    private static final Logger logger = LoggerFactory.getLogger(FooUpdatesHandler.class);
    private static final ConcurrentHashMap<String, ConcurrentHashMap<String, WebSocketSession>> fooSubscriptions =
            new ConcurrentHashMap<>();

    public static void sendFooToSubscribers(Foo foo) {
        Map<String, WebSocketSession> sessionMap = fooSubscriptions.get(foo.getId());

        if (sessionMap != null) {
            String fooJson = null;
            try {
                fooJson = new ObjectMapper().writeValueAsString(foo);
            } catch (JsonProcessingException ignored) {
                return;
            }

            for (WebSocketSession subscription : sessionMap.values()) {
                try {
                    logger.info("[fooId={} sessionId={}] Sending foo...", foo.getId(), subscription.getId());
                    subscription.sendMessage(new TextMessage(fooJson));
                    logger.info("[fooId={} sessionId={}] Foo send.", foo.getId(), subscription.getId());
                } catch (IOException e) {
                    logger.error("Socket sendFooToSubscribers [fooId={}], exception:  ", foo.getId(), e);
                }
            }
        }
    }
}

2 Answers 2

1

Just an educated guess: Check your networking gear. Maybe there is a misconfigured firewall terminating these connections; or even worse, broken networking gear causing the connections to terminate. If your server has multiple NICs (which is likely the case), it's also possible that there is some misconfiguration using these NICs, or in connecting to the server via different NICs.

3
  • The strange thing is, normally everything works great. Multiple devices (mobile and laptop) have a websocket connection and every device gets the JSONs of Foo. But sometimes (+/- once in 2 weeks), a "heavy" Broken Pipe occurs (see my comment at @Pavel Uvarov's answer). The websocket connection is still made and the server still sends heartbeats, it just doesn't send JSONs of Foo anymore. I don't think it's a firewall thing. Any other ideas?
    – J. Kamans
    Commented Nov 24, 2016 at 16:17
  • Does this affect any client after the "heavy" broken pipe - exception, or just the specific one which "caused" the exception?
    – Mr.Radar
    Commented Nov 24, 2016 at 17:38
  • It affects all clients. When it is broken (so no JSONs), a client contacts me. I test if it really is broken by opening the website in multiple tabs. All tabs have the same problem when the "heavy" Broken Pipe occurs. The only solution then is restarting the java program on the production server.
    – J. Kamans
    Commented Nov 24, 2016 at 17:54
1

If this problem occurs accidently than it is possible that you have some problem with any cache - please check if spring or SocksJS has own caches for socket interaction.

Is this happens on your devices (or on devices that you control)?

Additionally I can suggest you to use some network packet analyzer like wireshark. With such tool you'll see current network activity 'online'

Some external reasons that can desctroy connection without correct stopping it (and you cannot manage it without connection checkups):

  • device suspend/poweroff
  • network failure
  • browser closing on some error

I think that is a small part of full list of possible reasons to destroy connection.

5
  • It happens on mobile and laptops.
    – J. Kamans
    Commented Nov 24, 2016 at 16:06
  • There are different "kinds" of Broken Pipe Exceptions. I can generate one myself by refreshing the browser a lot, but after the last refresh everything still works fine (then server still sends the JSON of Foo to the client). But sometimes I get a Broken Pipe Exception that's so "heavy", the server does not send JSONs anymore (even when I refresh the page). The strange thing is, the server still sends heartbeats AND the server still logs "sending message" and "message send" (the logs before and after the Session.sendMessage method. I need to restart the whole java program to fix this...
    – J. Kamans
    Commented Nov 24, 2016 at 16:11
  • Any idea why that "heavy" Broken Pipe occurs? It is not because of your listed reasons unfortunately.
    – J. Kamans
    Commented Nov 24, 2016 at 16:14
  • @J.Kamans did you checked network interaction with any network packet analyzer? Commented Nov 24, 2016 at 16:31
  • I use Chrome, hit F12, go to tab Network. There I see "websocket" and I can see all websocket messages. I see the "o" (open), "h" (heartbeat) and also the JSON when everything works. ![Websocket frames Chrome.png](postimg.org/image/rf7dm6mmr)
    – J. Kamans
    Commented Nov 24, 2016 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.