websocket使用小例子

hulu321發表於2015-01-29
1、後臺程式碼Websocket.java
package com.sinosoft.tyoa.websocket;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")
public class Websocket {

private static Map<String,Session> sessionMap = new Hashtable<String,Session>();


@OnMessage
public void onMessage(String message, Session currentSession) {


/*// Send the message to the client
Set<Map.Entry<String,Session>> set = sessionMap.entrySet();
for (Map.Entry<String,Session> session: set) {
if(session.getValue().isOpen() == true) {
try {
System.out.println(session.getValue());
session.getValue().getBasicRemote().sendText(message);
} catch (IOException e) {
sessionMap.remove(session.getValue());
//e.printStackTrace();
}
}
else {
System.out.println("close:"+session.getValue());
sessionMap.remove(session.getValue());
}
}*/

//伺服器往各個客戶端傳送訊息
Iterator<String> iterator = sessionMap.keySet().iterator();
while(iterator.hasNext()) {
String key = (String) iterator.next();
Session session = sessionMap.get(key);
if(session.isOpen() == true) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
iterator.remove();
sessionMap.remove(key);
//e.printStackTrace();
}
}
else {
iterator.remove();
sessionMap.remove(key);
}
}
}

@OnOpen
public void onOpen(Session currentSession) {
if(sessionMap.containsValue(currentSession) == false){
sessionMap.put(currentSession.getId(), currentSession);
}
//System.out.println("Client connected");
}

@OnClose
public void onClose(Session currentSession) throws IOException{
sessionMap.remove(currentSession.getId());
//System.out.println("Client closed");
}

@OnError
public void onClose(Session currentSession,java.lang.Throwable throwable) throws IOException{
sessionMap.remove(currentSession.getId());
//System.out.println("Client closed");
}
}


2、pom.xml檔案配置
    <!-- websocket -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<!-- websocket end -->

3、前臺頁面
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = "ws" + "://"+ request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<script type="text/javascript">
var wsURI = "<%=basePath%>websocket";
var websocket = null;

function connectWebSocket(wsURI) {
if(websocket == null) {
websocket = new WebSocket(wsURI);
websocket.onopen = function(openEvent) {
$("#showMsg").append("連線成功...<br/>");
};
websocket.onclose = function(closeEvent) {
websocket == null;
$("#showMsg").append("關閉連線成功...<br/>");
};
websocket.onmessage = function(messageEvent) {
$("#showMsg").append("<span style='display:block'>" + messageEvent.data + "</span>");
};
websocket.onerror = function(errorEvent) {
//alert(errorEvent.data);
};
}
}

function sendMessageToClient(message) {
websocket.send(message);
}


$("#sendButton").click(function() {
sendMessageToClient($("#msg").val());
$("#msg").val("");
});


$(function(){
if(!("WebSocket" in window)){
alert("瀏覽器不支援!");
}
else {
connectWebSocket(wsURI);
}
});
</script>
<body>
<div id="showMsg" style="border: 1px solid; width: 500px; height: 400px; overflow: auto;"></div>
<div>
<input type="text" id="msg" />
<input type="button" id="sendButton" value="傳送" />
</div>
</body>




3、[color=red]出現錯誤可能原因:專案有攔截器,把/webscoket新增到可訪問路徑;jar包配置問題,tomcat7有支援jar包,所有pom.xml裡面要依賴jar包要設定編譯需要而釋出不需要。[/color]

相關文章