以下這段代碼是我復制Websocket4j中的一段實現webSocket服務器代碼。本來的程序是還有一個實現webSocket客戶端程序的。我執行那個客戶程序可以與此websocket服務器端通信。但我現在想把客戶端改為瀏覽器,於是我先eclipse中運行下面的程序的Java程序:
import java.io.IOException;
import websocket4j.server.WebServerSocket;
import websocket4j.server.WebSocket;
/**
* Example presenting an echo server using WebSocket4j.
*/
public class EchoServer extends Thread {
private WebSocket ws;
public EchoServer(WebSocket ws) {
this.ws = ws;
}
private void handleConnection() {
try {
while (true) {
String message = ws.getMessage();
ws.sendMessage(message);
System.out.println("Received: " + message);
if (message.equals("exit"))
break;
}
} catch (IOException e) {
}finally {
try {
ws.close();
} catch (IOException e) {
}
}
}
public void run() {
handleConnection();
}
public static void main(String[] args) throws IOException {
WebServerSocket socket = new WebServerSocket(5555);
try {
while (true) {
WebSocket ws = socket.accept();
System.out.println("GET " + ws.getRequestUri());
if (ws.getRequestUri().equals("/echo"))
(new EchoServer(ws)).start();
else {
System.out.println("Unsupported Request-URI");
try {
ws.close();
} catch (IOException e) {
}
}
}
} finally {
socket.close();
}
}
}
然後在chrome中運行HTML頁面:
<html>
<head>
<title>WebSoket Demo</title>
<script type="text/javascript">
if (!window.WebSocket) {
alert("WebSocket not supported by this browser!");
}
function display() {
var valueLabel = document.getElementById("valueLabel");
valueLabel.innerHTML = "";
var ws = new WebSocket(
"ws://localhost:5555");
ws.onmessage = function(evt) {
valueLabel.innerHTML = evt.data;
};
ws.onclose = function() {
};
ws.onopen = function() {
ws.send("/echo");
};
}
</script>
</head>
<body onload="display();">
<div id="valueLabel"></div>
</body>
</html>
刷新以上頁面時會讓服務器端Javat程序拋出以下異常信息:
Exception in thread "main" java.io.IOException: Handshake failed at websocket4j.AbstractWebSocket.<init>(Unknown Source) at websocket4j.server.WebSocket.<init>(Unknown Source) at websocket4j.server.WebServerSocket.accept(Unknown Source) at org.zou.websocket.EchoServer.main(EchoServer.java:75) Caused by: java.io.IOException: Unexpected header field: Sec-WebSocket-Key: xMj+0AdIFBLJcm7QBD7QbA== at websocket4j.server.WebSocket.handshake(Unknown Source) at websocket4j.AbstractWebSocket$HandshakeRunner.run(Unknown Source) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.lang.Thread.run(Unknown Source)
經調試這是上面服務器程序中的WebSocket ws = socket.accept();一句引發的。現在不知怎麼削除此異常,
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。