Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access instantiated WebSockets in Jetty 9?

This is probably obvious, but I am new to this paradigm. I create a Jetty Server and register my websocket class as follows:

        Server server = new Server(8080);
        WebSocketHandler wsHandler = new WebSocketHandler()
        {
            @Override
            public void configure(WebSocketServletFactory factory)
            {
                factory.register(MyEchoSocket.class);
            }
        };
        server.setHandler(wsHandler);

The websocket receives messages fine. I would like to also be able to send messages out from the server without having first received a message from the client. How do I access the MyEchoSocket instance that's created when the connection opens? Or, more generally, how do I send messages on the socket outside of the onText method in MyEchoSocket?

like image 280
Alex Pritchard Avatar asked Mar 26 '13 19:03

Alex Pritchard


People also ask

How do I activate Websockets?

- In Control Panel, click Programs and Features, and then click Turn Windows features on or off. Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then select WebSocket Protocol. Click OK. Click Close.

Can HTTP and WebSocket use same port?

Protocol handshake The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port.

How do I send a WebSocket request?

To send a message through the WebSocket connection you call the send() method on your WebSocket instance; passing in the data you want to transfer. socket. send(data); You can send both text and binary data through a WebSocket.

What is HTTP push WebSocket?

HTTP server push, also known as HTTP streaming, is a client-server communication pattern that sends information from an HTTP server to a client asynchronously, without a client request.


1 Answers

Two common techniques, presented here in a super simplified chatroom concept.

Option #1: Have WebSocket report back its state to a central location

@WebSocket
public class ChatSocket {
    public Session session;

    @OnWebSocketConnect
    public void onConnect(Session session) {
        this.session = session;
        ChatRoom.getInstance().join(this);
    }

    @OnWebSocketMessage
    public void onText(String message) {
        ChatRoom.getInstance().writeAllMembers("Hello all");
    }

    @OnWebSocketClose
    public void onClose(int statusCode, String reason) {
        ChatRoom.getInstance().part(this);
    }
}

public class ChatRoom {
    private static final ChatRoom INSTANCE = new ChatRoom();

    public static ChatRoom getInstance()
    {
        return INSTANCE;
    }

    private List<ChatSocket> members = new ArrayList<>();

    public void join(ChatSocket socket) 
    {
        members.add(socket);
    }

    public void part(ChatSocket socket) 
    {
        members.remove(socket);
    }

    public void writeAllMembers(String message) 
    {
        for(ChatSocket member: members)
        {
            member.session.getRemote().sendStringByFuture(message);
        }
    }

    public void writeSpecificMember(String memberName, String message) 
    {
        ChatSocket member = findMemberByName(memberName);
        member.session.getRemote().sendStringByFuture(message);
    }

    public ChatSocket findMemberByName(String memberName) 
    {
        // left as exercise to reader
    }
}

Then simply use the central location to talk to the websockets of your choice.

ChatRoom.getInstance().writeSpecificMember("alex", "Hello");

// or

ChatRoom.getInstance().writeAllMembers("Hello all");

Option #2: Have WebSocket be created manually with WebSocketCreator

@WebSocket
public class ChatSocket {
    public ChatRoom chatroom;

    public ChatSocket(ChatRoom chatroom)
    {
        this.chatroom = chatroom;
    }

    @OnWebSocketConnect
    public void onConnect(Session session) {
        chatroom.join(this);
    }

    @OnWebSocketMessage
    public void onText(String message) {
        chatroom.writeAllMembers(message);
    }

    @OnWebSocketClose
    public void onClose(int statusCode, String reason) {
        chatroom.part(this);
    }
}

public class ChatCreator implements WebSocketCreator
{
    private ChatRoom chatroom;

    public ChatCreator(ChatRoom chatroom)
    {
        this.chatroom = chatroom;
    }

    public Object createWebSocket(UpgradeRequest request, 
                                  UpgradeResponse response)
    {
        // We want to create the Chat Socket and associate
        // it with our chatroom implementation
        return new ChatSocket(chatroom);
    }
}

public class ChatHandler extends WebSocketHandler
{
    private ChatRoom chatroom = new ChatRoom();

    @Override
    public void configure(WebSocketServletFactory factory)
    {
        factory.setCreator(new ChatCreator(chatroom));
    }
}

At this point you can use the same techniques as above to talk to the websockets of your choice.

like image 147
Joakim Erdfelt Avatar answered Sep 27 '22 15:09

Joakim Erdfelt