Question

My code can work.But only refresh a page of one window.
If I open window1 and window2 , both open websocket connect.
I keyin word "test123" in window1, click sendbutton.
Only refresh window1.
How to refresh window1 and window2 ?
Client

<script>
window.onload = function() {
    document.getElementById('sendbutton').addEventListener('click', sendMessage,false);
    document.getElementById('connectbutton').addEventListener('click', connect, false);        
}

function writeStatus(message) {
    var html = document.createElement("div");
    html.setAttribute('class', 'message');
    html.innerHTML = message;
    document.getElementById("status").appendChild(html);
}
function connect() {
    ws = new WebSocket("ws://localhost:9000/ws?name=test");
    ws.onopen = function(evt) { 
        writeStatus("connected");
    }        
    ws.onmessage = function(evt) {
        writeStatus("response: " + evt.data);
    }        
}

function sendMessage() {
    ws.send(document.getElementById('messagefield').value);
}
</script>
</head>
<body>    
<button id="connectbutton">Connect</button>    
<input type="text" id="messagefield"/>
<button id="sendbutton">Send</button>
<div id="status"></div>   
</body>

Play Framework WebSocketController

public class WebSocket extends WebSocketController {
public static void test(String name) {

    while(inbound.isOpen()) {
        WebSocketEvent evt = await(inbound.nextEvent());
        if(evt instanceof WebSocketFrame) {
            WebSocketFrame frame = (WebSocketFrame)evt;
            System.out.println("received: " + frame.getTextData());
            if(!frame.isBinary()) {
                if(frame.getTextData().equals("quit")) {
                    outbound.send("Bye!");
                    disconnect();
                } else {
                        outbound.send("Echo: %s", frame.getTextData());
                    }
                }
            } 
        }
     }
 }
Was it helpful?

Solution

You have the basic of making work a single socket. However, each socket you are creating uses your socket events. Since each of the sockets would equal a thread, you need to send the event for each socket you can have. This is why when a new socket is open you need to map it in an array of sockets.

This thread can help you out.

Websocket send data all client in playframework 2

And refer to this exemple of play with framework.

https://github.com/playframework/playframework/blob/master/samples/java/websocket-chat/app/models/ChatRoom.java#L89

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top