基于HTML5和Tomcat WebSocketServlet的聊天室简单实现

 

index.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<%  
    String path = request.getContextPath();  
    String WsBasePath = "ws://" + request.getServerName() + ":"  
            + request.getServerPort() + path + "/";  
%>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>websocket聊天室</title>  
<style type="text/css">  
#chat {  
    text-align: left;  
    width: 600px;  
    height: 500px;  
    width: 600px;  
}  
  
#up {  
    text-align: left;  
    width: 100%;  
    height: 400px;  
    border: 1px solid green;  
    OVERFLOW-Y: auto;  
}  
  
#down {  
    text-align: left;  
    height: 100px;  
    width: 100%;  
}  
</style>  
</head>  
<body>  
    <h2 align="center">基于HTML5的聊天室</h2>  
    <div align="center" style="width: 100%; height: 700px;">  
        <div id="chat">  
            <div id="up"></div>  
            <div id="down">  
                <textarea style="width: 602px; height: 100%;" id="send"></textarea>  
            </div>  
        </div>  
        <br/>  
        <input type="button" value="连接" οnclick="chat(this);"> <input  
            type="button" value="发送" οnclick="send(this);" disabled="disabled"  
            id="send_btn" title="Ctrl+Enter发送">  
    </div>  
</body>  
<script type="text/javascript">  
    var socket;  
    var receive_text = document.getElementById("up");  
    var send_text = document.getElementById("send");  
    function addText(msg) {  
        receive_text.innerHTML += "<br/>" + msg;  
        receive_text.scrollTop = receive_text.scrollHeight;  
    }  
    var chat = function(obj) {  
        obj.disabled = "disabled";  
        try{  
            socket = new WebSocket('<%=WsBasePath + "chat"%>');  
            receive_text.innerHTML += "<font color=green>正在连接服务器……</font>";  
        }catch(e){  
            receive_text.innerHTML += "<font color=red>抱歉,您的浏览器不支持html5,请使用IE10或者最新版本的谷歌、火狐等浏览器!</font>";  
        }  
        //打开Socket   
        socket.onopen = function(event) {  
            falg=false;  
            addText("<font color=green>连接成功!</font>");  
            document.getElementById("send_btn").disabled = false;  
            send_text.focus();  
            document.onkeydown = function(event) {  
                if (event.keyCode == 13 && event.ctrlKey) {  
                    send();  
                }  
            };  
        };  
        socket.onmessage = function(event) {  
            addText(event.data);  
        };  
  
        socket.onclose = function(event) {  
            addText("<font color=red>连接断开!</font>");  
            obj.disabled = "";  
        };  
    };  
    var send = function(obj) {  
        if (send_text.value == "") {  
            return;  
        }  
        socket.send(send_text.value);  
        send_text.value = "";  
        send_text.focus();  
    };  
</script>  
</html>


 

ChatWebSocketServlet.java

 

    package com.baiyang.lc.websocketservlet;  
      
    import java.io.IOException;  
    import java.nio.ByteBuffer;  
    import java.nio.CharBuffer;  
    import java.text.SimpleDateFormat;  
    import java.util.Date;  
    import java.util.HashMap;  
    import java.util.Map;  
    import java.util.Set;  
      
    import javax.servlet.annotation.WebServlet;  
    import javax.servlet.http.HttpServletRequest;  
      
    import org.apache.catalina.websocket.MessageInbound;  
    import org.apache.catalina.websocket.StreamInbound;  
    import org.apache.catalina.websocket.WebSocketServlet;  
    import org.apache.catalina.websocket.WsOutbound;  
      
    @WebServlet("/chat")  
    public class ChatWebSocketServlet extends WebSocketServlet {  
        private final Map<Integer, WsOutbound> map = new HashMap<Integer, WsOutbound>();  
      
        /** 
         *  
         */  
        private static final long serialVersionUID = -1058445282919079067L;  
      
        @Override  
        protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) {  
            return new ChatMessageInbound();  
        }  
      
        class ChatMessageInbound extends MessageInbound {  
      
            @Override  
            protected void onOpen(WsOutbound outbound) {  
                map.put(outbound.hashCode(), outbound);  
                super.onOpen(outbound);  
            }  
      
            @Override  
            protected void onClose(int status) {  
                map.remove(getWsOutbound().hashCode());  
                super.onClose(status);  
            }  
      
            @Override  
            protected void onBinaryMessage(ByteBuffer buffer) throws IOException {  
                // TODO Auto-generated method stub  
      
            }  
      
            @Override  
            protected void onTextMessage(CharBuffer buffer) throws IOException {  
                String msg = buffer.toString();  
                Date date = new Date();  
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");  
                msg = " <font color=green>匿名用户  " + sdf.format(date) + "</font><br/> " + msg;  
                broadcast(msg);  
            }  
      
            private void broadcast(String msg) {  
                Set<Integer> set = map.keySet();  
                for (Integer integer : set) {  
                    WsOutbound outbound = map.get(integer);  
                    CharBuffer buffer = CharBuffer.wrap(msg);  
                    try {  
                        outbound.writeTextMessage(buffer);  
                        outbound.flush();  
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
    }  


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值