1, 前端代码 登入页 -> login.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>聊天室登入接口</title>
    <script type="text/javascript" src="JavaScript/jQuery.js"></script>
</head>
<body>
    请输入账号名: <input id="UserName" type="text" value="">
    <input id="Submit" type="submit" value="登入">
</body>
<script type="text/javascript">
    $('#Submit').on('click', function(){
        var userName = $('#UserName').val().trim();
        if(userName == ''){
            console.error("账号名不能为空")
            return;
        }
        location.href = "ChatRoom.html?UserName=" + userName;
    });
</script>
</html>

2, 前端代码 聊天页面 -> ChatRoom

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <script type="text/javascript" src="JavaScript/jQuery.js"></script>
    <style type="text/css">
        *{ margin: 0; padding: 0; outline: none; border: none; float: left;}
        #Chat{
            width: 800px;
            height: 600px;
            border: 1px solid #000000;
            margin: 20px 0 0 20px;
        }
        #Content{
            width: 600px;
            height: 400px;
            overflow-y: scroll;
            border-bottom: 1px solid black;
            border-right: 1px solid black;
        }
        .ContentList{
            width: 100%;
            border-bottom: 1px solid #CCC;
            padding: 5px 0 10px 0; 
        }
        .User{
            width: 30%;
            line-height: 20px;
            font-size: 16px;
            color: red;
            text-indent: 10px;
        }
        .Time{
            width: 70%;
            line-height: 20px;
            font-size: 14px;
            text-indent: 10px;
        }
        .Text{
            margin: 8px 0 0 0;
            width: 100%;
            line-height: 20px;
            font-size: 14px;
            text-indent: 28px;
        }
        #UserList{
            border-bottom: 1px solid black;
            height: 400px;
            width: 199px;
            overflow-y: scroll;
        }
        #UserList > div{
            width: 100%;
            line-height: 28px;
            font-size: 16px;
            text-indent: 32px;
            color: green;
            border-bottom: 1px solid #CCC;
        }
        #InputFrame{
            width: 800px;
            height: 199px;
        }
        .input{
            width: 98%;
            height: 169px;
            display: block;
            line-height: 30px;
            font-size: 18px;
            font-weight: bold;
            padding: 0 0 0 2%;
            border-bottom: 1px solid #CCC;
        }
        .submit{
            width: 100px;
            height: 29px;
            padding: 5px;
            float: right;
            margin: 0 0 0 10px;
        }
    </style>
</head>
<body>
    <div id="Chat">
        <div id="Content">
            
        </div>
        <div id="UserList">

        </div>
        <div id="InputFrame">
            <textarea class="input"></textarea>
            <input class="submit" type="button" value="发送">
            <input class="submit" type="button" value="取消">
        </div>
    </div>
</body>
<script type="text/javascript">
    // GET 传值的获取方法 
    (function($){
        var url = location.search.substring(1);
        var atr = url.split('&');
        var value = {};
        for(var i = 0; i < atr.length; i ++){
            value[atr[i].split('=')[0]] = decodeURIComponent(atr[i].split('=')[1]);
        }
        $.extend({
            GetUrlValue : function(key){
                return  value[key];
            }
        });
    })(jQuery);
    
    // 创建 WebSocket 的方法 
    function createWebSocket(urlValue){
        if("WebSocket" in window){
            return new WebSocket(urlValue);
        } 
        if ("MozWebSocket" in window){
            return new MozWebSocket(urlValue);
        }
        console.error("浏览器不支持 WebSocKet");
    }
    
    // 构建请求的地址
    var requestUrl = "ws://192.168.0.103/WebTest/ChatRoomForWebSocket?UserName=" + $.GetUrlValue("UserName");
    var webSocket = createWebSocket(requestUrl);
    webSocket.onmessage = function(e){
        console.log(e.data);
        if(e.data == "error"){
            alert("用户名已经被占用,请重新登入!");
            location.href = "Login.html";
        }
        e = $.parseJSON(e.data);
        if(e.type == '0'){
            var data = e.data;
            var str = "";
            for(var i = 0; i < data.length; i++){
                str += '<div>'+ data[i].name +'</div>';
            }
            $('#UserList').html(str);
        }
        if(e.type == '1'){
            var data = e.data;
            var str = '<div class="ContentList">';
            str += '<div class="User">'+ data.name +'</div>';
            str += '<div class="Time">'+ data.time +'</div>';
            str += '<div class="Text">'+ data.msg +'</div>';
            str += '</div>';
            $('#Content').append(str);
        }
    }
    
    $('.submit').on('click', function(){
        var inputValue = $(this).val();
        if(inputValue == "发送"){
            var sendValue = $('.input').val().trim();
            if(sendValue == ''){
                alert("发送内容不能为空");
            } else {
                // 将换行符替换为 <br> 标签
                sendValue = sendValue.replace(/\n/g, "<br>");
                webSocket.send(sendValue);
            }
        }
        $('.input').val('');
    });
</script>
</html>

3, JAVA后台处理代码 WebSocket需要配置才能起作用,

  如何配置请参考另一篇 http://www.cnblogs.com/lovling/p/6716612.html

package socket_web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

@ServerEndpoint("/ChatRoomForWebSocket")
public class ChatRoomForWebSocket {
    public static List<String> userNames = new ArrayList<String>();
    public static List<Session> sessions = new ArrayList<Session>();

    @OnOpen
    public void open(Session session) {
        try {
            String userName = session.getQueryString();
            userName = userName.split("=")[1];
            userName = URLDecoder.decode(userName, "utf-8");
            
            if (userNames.contains(userName)) {
                session.getBasicRemote().sendText("error");
            } else {
                userNames.add(userName);
                sessions.add(session);
                String msg = "{\"type\":0, \"data\":[" + jsonName() + "]}";
                pushMsg(msg);
            }
            System.out.println(userName + " 登入了");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void close(Session session) {
        try {
            String userName = session.getQueryString();
            userName = userName.split("=")[1];
            userName = URLDecoder.decode(userName, "utf-8");
            if (sessions.contains(session)){
                userNames.remove(userName);
                sessions.remove(session);
            }
            String msg = "{\"type\":0, \"data\":[" + jsonName() + "]}";
            pushMsg(msg);
        } catch (Exception e) {
            System.out.println("关闭失败");
        }
    }

    @OnMessage
    public void message(Session session, String msg) {
        try {
            String userName = session.getQueryString();
            userName = userName.split("=")[1];
            userName = URLDecoder.decode(userName, "utf-8");
            Date date = new Date();
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = timeFormat.format(date);
            msg = "{\"type\":1, \"data\":{\"name\":\"" + userName + "\", \"msg\":\"" + msg + "\",\"time\":\"" + time
                    + "\" }}";
            pushMsg(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    // 推送消息给所有用户
    public static void pushMsg(String msg) {
        try {
            for (Session session : sessions) {
                session.getBasicRemote().sendText(msg);
            }
        } catch (Exception e) {
            System.out.println("发送失败");
        }
    }

    // 拼接所有用户名
    public static String jsonName() {
        StringBuilder nameStr = new StringBuilder(100);
        for (String name : userNames) {
            nameStr.append("{\"name\":\"" + name + "\"},");
        }
        nameStr.delete(nameStr.length() - 1, nameStr.length());
        return nameStr.toString();
    }
}

 

posted on 2017-04-16 18:21  被遗忘的优雅  阅读(824)  评论(0编辑  收藏  举报