准备工具:
tomcat7+
jdk7+ (webscoket是javaee7的新特性,所以必须版本是7及以上.)
创建工程:
创建一个名为webscoket的工程.
java文件如下:
03 | import java.io.IOException; |
04 | import java.util.Hashtable; |
07 | import java.util.logging.Logger; |
09 | import javax.websocket.CloseReason; |
10 | import javax.websocket.CloseReason.CloseCodes; |
11 | import javax.websocket.OnClose; |
12 | import javax.websocket.OnError; |
13 | import javax.websocket.OnMessage; |
14 | import javax.websocket.OnOpen; |
15 | import javax.websocket.RemoteEndpoint; |
16 | import javax.websocket.Session; |
17 | import javax.websocket.server.PathParam; |
18 | import javax.websocket.server.ServerEndpoint; |
20 | @ServerEndpoint (value = "/game" ) |
23 | private Logger logger = Logger.getLogger( this .getClass().getName()); |
25 | static Map<String,Session> sessionMap = new Hashtable<String,Session>(); |
28 | public void onOpen(Session session) { |
29 | sessionMap.put(session.getId(), session); |
33 | public void onMessage(String unscrambledWord, Session session) { |
34 | broadcastAll( "message" ,unscrambledWord); |
40 | public static void broadcastAll(String type,String message){ |
41 | Set<Map.Entry<String,Session>> set = sessionMap.entrySet(); |
42 | for (Map.Entry<String,Session> i: set){ |
44 | i.getValue().getBasicRemote().sendText( "{type:'" +type+ "',text:'" +message+ "'}" ); |
45 | } catch (Exception e) { |
52 | public void onClose(Session session, CloseReason closeReason) { |
53 | sessionMap.remove(session.getId()); |
54 | logger.info(String.format( "Session %s closed because of %s" , session.getId(), closeReason)); |
58 | public void error(Session session, java.lang.Throwable throwable){ |
59 | sessionMap.remove(session.getId()); |
60 | System.err.println( "session " +session.getId()+ " error:" +throwable); |
创建一个注解为:@ServerEndpoint的webscoket的服务端.供前台访问.因为想实现点其它功能.所以在广播给所有人这个方法里边加上了type以备区分
注解说明图:
接下来是jsp页面.直接上代码..
01 | <%@ page language="java" contentType="text/html; charset=UTF-8" |
02 | pageEncoding="UTF-8"%> |
06 | < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" > |
07 | < title >Insert title here</ title > |
09 | < script type = "text/javascript" > |
12 | function parseObj(strData){//转换对象 |
13 | return (new Function( "return " + strData ))(); |
16 | socket = new WebSocket("ws://"+ window.location.host+"/${pageContext.request.contextPath}/game"); |
18 | socket.onopen = function() { |
19 | $("#showMsg").append("连接成功...< br />"); |
22 | socket.onmessage = function(message) { |
23 | var data=parseObj(message.data); |
24 | if(data.type=="message"){ |
25 | $("#showMsg").append("< span style = 'display:block' >"+data.text+"</ span >"); |
26 | }else if(data.type=="background"){ |
27 | $("#showMsg").append("< span style = 'display:block' >系统改变背景地址,背景地址是:"+data.text+"</ span >"); |
28 | $("body").css("background","url("+data.text+")"); |
32 | socket.onclose = function(){ |
36 | socket.onerror = function() { |
39 | $("#sendButton").click(function() { |
40 | socket.send($("#msg").val()); |
42 | $("#abcde").click(function(){ |
43 | $.post("${pageContext.request.contextPath}/backgroundimg"); |
49 | < div id = "showMsg" style = "border: 1px solid; width: 500px; height: 400px; overflow: auto;" ></ div > |
51 | < input type = "text" id = "msg" /> |
52 | < input type = "button" id = "sendButton" value = "发送" /> |
53 | < input type = "button" value = "改变背景" id = "abcde" /> |
基本上就可以简单的实现了多人聊天功能了.或者集体换背景图片功能.
自己感兴趣的可以根据实际业务需求做一定的扩展.
等工作空下来会做进一步的进阶.再发文章出来.