基于websocket的多人页面聊天室

来源:互联网 发布:淘宝网的运费险怎么用 编辑:程序博客网 时间:2024/05/21 10:23

这是一个简单的页面聊天室。关于websocket是什么,看看这篇回答吧,要知道它是一个持久化的协议。
在项目中登录注册我就不讲了,直接从聊天室开始吧。

页面js

var socket =null;var user =null;function parseObj(strData){//change string to obj    return (new Function( "return " + strData ))();};//dbclick to kickfunction userdbClick(obj){    if(user.type!=""&&user.type=="1"){        socket.send("kick#"+$(obj).attr("id"));    }else{        alert("You can`t kick him/her");    }};//if browser supports WebSocket   if (!window.WebSocket) {         alert("WebSocket not supported by this browser!");    }  $(function(){      if('${user}'==""){        alert("please login in ");        window.location.href="login.jsp";     }else{        user = eval('(' + '${user}' + ')');        $("#myname").text(user.name);        var myt;        if(user.type==1){            myt="Admin";        }else{            myt="User";        }        $("#mytype").text(myt);        //create socket object        socket = new WebSocket("ws://"+ window.location.host+"/${pageContext.request.contextPath}/chat");        socket.onopen = function() {            $("#showMsg").append("Connection Successful...<br/>");            socket.send("add#"+user.id);        };        socket.onmessage = function(message) {            var data=parseObj(message.data);            //if have been kicked ,goto login.jsp            if(typeof(data.type)!= "undefined"){                if(data.type=="kick"){                    alert(data.message);                    window.location.href="login.jsp";                     return;                }            }            //show the msg to screen            $("#showMsg").append("<span style='display:block'>"+data.message+"</span>");            //update the user list while receive the msg from server            var users=data.users;            if(typeof(users)!= "undefined"){                $("#users").empty();                $("#users").append("<option value='0'>all</option>");                $("#userlist").empty();                $.each( users, function(i, n){                      if(n.id==user.id){                      }else{                          $("#users").append("<option value='"+n.id+"'>"+n.name+"</option>");                      }                      var t=n.type==1;                      if(n.id==user.id){                          alert("<c:if test='"+n.type+"==1'>A--</c:if>");                          $("#userlist").append("<p id='"+n.id+"'  class='my'><c:choose><c:when test='"+t+"'>A--</c:when><c:otherwise>U--</c:otherwise></c:choose>"+n.name+"</p>");                      }else{                        $("#userlist").append("<p id='"+n.id+"' ondblclick='userdbClick(this);'><c:choose><c:when test='"+t+"'>A--</c:when><c:otherwise>U--</c:otherwise></c:choose>"+n.name+"</p>");                      }                });            }        };        //when leave the page        socket.onclose = function(){            <%session.setAttribute("user","");%>              socket.send('leave#');            window.location.href="login.jsp";         };        //when error        socket.onerror = function() {            alert("error");        };        //send msg to others or only one        $("#sendButton").click(function() {            if($("#users").val()!=0){                socket.send("sendone#"+$("#msg").val()+"#"+$("#users").val());            }else{                socket.send("sendall#"+$("#msg").val());            }            $("#msg").val("");        });        //leave the chat room        $("#leaveButton").click(function(){            window.location.href="login.jsp";             socket.send('leave');        });        //change the user state        $("#state").change(function(){            var state=$("#state").val();            socket.send("state#"+state);        });    }});

server java

这个类中的方法基本与js中的对应,这个OnMessage方法主要是根据页面传过来的数据进行分类处理

    @OnMessage    public void onMessage(String unscrambledWord, Session session, EndpointConfig config){        String[] str=unscrambledWord.split("#");        User user=getUserBySession(session);        if("leave".equals(str[0])){//user leave            user.getHttpSession().setAttribute("user", "");        }else if("sendone".equals(str[0])){//send one user            JSONObject json=new JSONObject();            json.put("message", "["+new Date()+"]"+user.getName()+" send to "+userList.get(str[2]).getName()+"<br/>"+str[1]);            broadcastToOne(json,str[2],user);        }else if("sendall".equals(str[0])){//send all users            JSONObject json=new JSONObject();            json.put("message", "["+new Date()+"]"+user.getName()+"<br/>"+str[1]);            broadcastAllUser(json);        }else if("add".equals(str[0])){//new user come in            userList.get(str[1]).setSession(session);            JSONObject json=new JSONObject();            String welcome="*****welcome,"+userList.get(str[1]).getName()+"! *****";            json.put("message", welcome);            json.put("users", getUserList());            broadcastAllUser(json);        }else if("state".equals(str[0])){//change user`s state            user.setState(str[1]);        }else if("kick".equals(str[0])){//kick user            if(user.getType().equals("1")){                String outid=str[1];                JSONObject json=new JSONObject();                json.put("message", "You been kicked !");                json.put("type", "kick");                user.getHttpSession().setAttribute("user", "");                kick(json,outid);            }        }else{            JSONObject json=new JSONObject();            json.put("message", user.getName()+"   "+new Date()+unscrambledWord);            broadcastAllUser(json);        }    }

demo 下载地址:http://download.csdn.net/detail/wujiaoyan0423/9506595

0 0
原创粉丝点击