<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Demo Chat</title>
    <style>
        body {
            padding:20px;
        }
        #console {
            height: 400px;
            overflow: auto;
        }
        .username-msg {color:orange;}
        .connect-msg {color:green;}
        .disconnect-msg {color:red;}
        .send-msg {color:#888}
    </style>
    <meta rel="stylesheet" src="${pageContext.request.contextPath }/jsp/css/bootstrap.min.css">
    <script src="${pageContext.request.contextPath }/jsp/js/bootstrap.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.5.0/socket.io.js"></script>
    <script src="${pageContext.request.contextPath }/jsp/js/moment.min.js"></script>
    <script src="${pageContext.request.contextPath }/jsp/js/jQuery.js"></script>
    <script>
        var userName = 'user' + Math.floor((Math.random()*1000)+1);

        //创建通道连接
        var socket =  io.connect('http://localhost:8090?userId=79');

        socket.on('connect', function() {
            output('<span class="connect-msg">Client has connected to the server!</span>');
        });

        socket.on('chatevent', function(message) {
            output('<span class="username-msg">' + message.userName + ':</span> ' + message.message);
        });

        socket.on('disconnect', function() {
            output('<span class="disconnect-msg">The client has disconnected!</span>');
        });

        //关闭通道连接 可被@OnDisconnect注解的方法监听
        function sendDisconnect() {
            socket.disconnect();
        }

        function sendMessage() {
            var message = $('#msg').val();
            $('#msg').val('');
            var jsonObject = {
                userId: 79,
                userName: userName,
                message: message
            };
            //发往后端@OnEvent("chatevent")注解的方法
            socket.emit('chatevent', jsonObject);
        }

        function output(message) {
            var currentTime = "<span class='time'>" +  moment().format('HH:mm:ss.SSS') + "</span>";
            var element = $("<div>" + currentTime + " " + message + "</div>");
            $('#console').prepend(element);
        }

        $(document).keydown(function(e){
            if(e.keyCode == 13) {
                $('#send').click();
            }
        });
    </script>
</head>

<body>

<h1>Netty-socketio Demo Chat</h1>
<br/>
<div id="console" class="well">
</div>
<form class="well form-inline" onsubmit="return false;">
    <input id="msg" class="input-xlarge" type="text" placeholder="Type something..."/>
    <button type="button" onClick="sendMessage()" class="btn" id="send">Send</button>
    <button type="button" onClick="sendDisconnect()" class="btn">Disconnect</button>
</form>

</body>
</html>
