我的代码可以工作。但只刷新一个窗口的一页。
如果我打开 window1 和 window2 ,都打开 websocket 连接。
我在window1中键入单词“test123”,单击发送按钮。
只刷新window1。
如何刷新 window1 和 window2 ?
客户
<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>
播放框架 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());
}
}
}
}
}
}