[英]How to get a websocket in glassfish 4 and jsf working?
这是我的代码,我的js工作,但是当您尝试向websocket发送消息时:glassfish返回:
INFO: Error : SessionImpl{uri=/Formosa2/endpoint, id='b821d249-6435-45fe-812d- 577bc5fc8fca', endpoint=EndpointWrapper{endpointClass=null, endpoint=org.glassfish.tyrus.core.AnnotatedEndpoint@1602760, uri='/Formosa2/endpoint', contextPath='/Formosa2'}}
@ServerEndpoint(value = "/endpoint")
@Singleton
public class websocket {
private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
@OnMessage
public void onMessage(String message) {
String filteredMessage = String.format("%s: %s", message.toString());
broadcast(filteredMessage);
System.out.println(message);
}
@OnOpen
public void onOpen(Session peer){
peers.add(peer);
String message = String.format("* %s %s", "User has joined.");
broadcast(message);
}
@OnClose
public void onClose(Session peer){
peers.remove(peer);
}
@OnError
public void onError(Session aclientSession, Throwable aThrowable) {
System.out.println("Error : " + aclientSession);
}
private void broadcast(String message) {
for (Session peer : peers) {
try {
CharBuffer buffer = CharBuffer.wrap(message);
peer.getBasicRemote().sendText(buffer.toString());
} catch (IOException ignore) {
// Ignore
}
}
}
}
和
<script type="text/javascript">
ws = new WebSocket('ws://' + window.location.host + '/Formosa2/endpoint'); //Annotation
ws.onopen = function(event) {
Console.log('Info: WebSocket connection opened.');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
sendMessage();
}
};
};
ws.onmessage = function(event) {
sendMessage(event);
};
ws.onclose = function(event) {
document.getElementById('chat').onkeydown = null;
Console.log('Info: WebSocket closed.');
};
ws.onerror = function(event){
alert("Error : " + event.data);
Console.log(message.data);
};
function sendMessage (event) {
var text = document.getElementById('form:texto').value;
var select = document.getElementById('form:empresaidEmpresa');
var text2 = document.getElementById('inicio_input').value;
var name = select.options[select.selectedIndex].text;
ws.send(texto +', '+ name +',' + text2);
document.getElementById('chat').value = '';
}
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
// Chat.initialize();
</script>
String message = String.format("* %s %s", "User has joined.");
这行是格式修饰符不正确的问题,我能够通过读取aThrowable参数的日志(system.out ..)来发现这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.