websocket及时通讯

基础

server.js

var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {});
server.listen(3000, function() {
    console.log('服务器启动成功');
});
wsServer = new WebSocketServer({
    httpServer: server
});
wsServer.on('request', function(request) {
    var connection = request.accept(null, request.origin);
    setInterval(function(){
        connection.sendUTF('我持续发消息')
    },1000)
    console.log('连接成功');
    connection.on('close', function(reasonCode, description) {
        console.log('连接已断开');
    });
});

test.html

<script>
        var ws = new WebSocket('ws://localhost:3000');
        ws.onopen = function(res){
            console.log('连接成功')
        }
        ws.onmessage = function(res){
            console.log('有新消息')
        }
    </script>
聊天室

serCenter.js

var WebSocketServer = require('websocket').server;
var http = require('http');
 
var server = http.createServer();
server.listen(3000,function(){//服务器启动时
    console.log('服务器搭建成功')
})
var wsServer = new WebSocketServer({httpServer:server})//用服务器创建socket
var clients = []
wsServer.on('request', function(request) {//连接成功时
    var connection = request.accept(null, request.origin);
    clients.push(connection)
    connection.on('message', function(message) {//接收到消息时
        if (message.type === 'utf8') {
            clients.forEach(function(item){
                item.sendUTF(message.utf8Data)
            })
        }
        else if (message.type === 'binary') {
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {//连接断开时
        console.log(connection.remoteAddress + '连接已断开');
        var index = clients.indexOf(connection)
        clients.splice(index,1)
    });
})

oneClient.html

<body>
    <ul id="content"></ul>
    <input type="text" id="msg">
    <button onclick="send()">发送</button>
    <script>
        var ws = new WebSocket('ws://localhost:3000')
        var inputNode = document.getElementById('msg')
        var content = document.getElementById('content')
        ws.onmessage  = function(msg){
            console.log(msg)
            content.innerHTML +='<li>'+msg.data+'</li>'
        }
    function send(){
        ws.send(inputNode.value)
    }
    </script>
</body>

在这里插入图片描述
cnpm i websocket
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值