最近剛剛學習了JSP/Servlet的知識,書上有講WebSocket的技術,自己想實現一下,但總是有問題,如下圖:
源代碼如下:
/*頁面腳本*/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>使用WebSocket通信</title>
<script type="text/javascript">
var webSocket=new WebSocket("ws://127.0.0.1:8080/WebSocket/websocket/chat");
var sendMsg=function()
{
var inputElement=document.getElementById('msg');
//發送信息
webSocket.send(inputElement.value);
//清空單行文本框
inputElement.value="";
};
var send=function(event)
{
if(event.keyCode==13)
{
sendMsg();
}
};
webSocket.onopen = funcntion()
{
alert("hello webSocket!");
//為onmessage事件綁定監聽器,接收消息
webSocket.onmessage = function(event) {
var show = document.getElementById('show');
//接收並顯示消息
show.innerHTML+= event.data + "<br/>";
show.scrollTop = show.scrollHeight;
}
document.getElementById('msg').onkeydown = send;
document.getElementById('sendBn').onclick = sendMsg;
};
webSocket.onclose = function() {
document.getElementById('msg').onkeydown = null;
document.getElementById('sendBn').onclick = null;
Console.log('WebSocket已經關閉。');
};
</script>
</head>
<body>
<div style="width:600px; height:240px; overflow-y:auto;border:1px solid #333;" id="show"></div>
<input type="text" size="80" id="msg" name="msg" placeholder="輸入聊天內容"/>
<input type="button" value="發送" id="sendBn" name="sendBn"/>
</body>
</html>
//實現的Java類
package com.xlf;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/websocket/chat")
public class ChatEntpoint {
private static final String GUEST_PREFIX = "訪客";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
// 定義一個集合,用於保存所有接入的WebSocket客戶端
private static final Set<ChatEntpoint> clientSet = new CopyOnWriteArraySet<ChatEntpoint>();
private final String nickname;
private Session session;
public ChatEntpoint() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
// 當客戶端連接進來時自動激發該方法
@OnOpen
public void start(Session session) {
this.session = session;
clientSet.add(this);
String message = String.format("[%s %s]", nickname, "加入了聊天室!");
broadcast(message);
}
// 當客戶端斷開連接時自動激發該方法
@OnClose
public void end() {
clientSet.remove(this);
String message = String.format("[%s %s]", nickname, "離開了聊天室!");
broadcast(message);
}
// 每當收到客戶端消息時自動激發該方法
@OnMessage
public void incoming(String message) {
String filterMessage = String
.format("%s %s", nickname, filter(message));
broadcast(filterMessage);
}
public static void broadcast(String msg) {
for (ChatEntpoint client : clientSet) {
try {
synchronized (client) {
//發送消息
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
System.out.println("聊天錯誤,向客戶端 "+client+" 發送消息出現錯誤。");
clientSet.remove(client);
try {
client.session.close();
} catch (IOException e1) {}
String message=String.format("[%s %s]", client.nickname,"已經被斷開了");
broadcast(message);
}
}
}
public static String filter(String message){
if(message==null)
return null;
char content[]=new char[message.length()];
message.getChars(0, message.length(), content, 0);
StringBuilder result=new StringBuilder(content.length+50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
default:
result.append(content[i]);
break;
}
}
return (result.toString());
}
}
新人,希望有大神指教!
應該是function() 拼寫錯誤吧?