node 版websocket的处理

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link href="../bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
    <script src="../js/jquery-1.12.3.min.js"></script>
    <script src="../bootstrap-3.3.5/js/bootstrap.min.js"></script>
</head>

<body>

    <div class="vertical-center">
        <div class="container">
            <!-- 客户端加一个简单的input输入框和一个发送按钮 -->
            <form role="form" id="chat_form" onsubmit="sendMessage(); return false;" style="margin-top:100px;">
                <div class="form-group">
                    <input class="form-control" type="text" name="message" id="message" value="" />
                </div>
                <button type="button" id="send" class="btn btn-primary" onclick="sendMessage();">
                    发送
                </button>
            </form>
        </div>
    </div>
</body>
<script>
    //WebSocket实例化
    var ws = new WebSocket("ws://localhost:8181");
    ws.onopen = function (e) {
        //成功连接服务器回调
        console.log('客户端(client):与服务器的连接已打开')
    }

    function sendMessage() {
        ws.send($('#message').val());
    };
</script>

</html>

后端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link href="../bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
    <script src="../js/jquery-1.12.3.min.js"></script>
    <script src="../bootstrap-3.3.5/js/bootstrap.min.js"></script>
</head>

<body>

    <div class="vertical-center">
        <div class="container">
            <form role="form" id="chat_form" onsubmit="sendMessage(); return false;" style="margin-top:100px;">
                <div class="form-group">
                    <input class="form-control" type="text" name="message" id="message" value="" />
                </div>
                <button type="button" id="send" class="btn btn-primary" onclick="sendMessage();">
                    发送
                </button>
            </form>
        </div>
    </div>
</body>
<script>
    //WebSocket实例化
    var ws = new WebSocket("ws://localhost:8181");
    ws.onopen = function (e) {
        //成功连接服务器回调
        console.log('客户端(client):与服务器的连接已打开')
    }

    function sendMessage() {
        ws.send($('#message').val());
    };
</script>

</html>
原创文章 207 获赞 173 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/104046215