nodejs+websocket使用

先npm安装websocket

websocket全双工通讯协议tcp(一直保持着长连接)
http是一个无状态的无连接,单向的应用层协议,采用了请求/响应模式,通讯请求只能由客户端发起,服务端应答,无法实现主动向客户端发起消息,
先new一个websocket(参数:用户参数和url组成一个新的url)。open是与服务器建立连接,onmessage是接收后端发过来的数据,send(value)客户端发送数据

npm install websocket

nodejs中server.js

var WebSocketServer = require('websocket').server;//引入模块
var http = require('http');//需要底层的http模块

//创建服务器
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
//监听3000端口
server.listen(3000, function() {
    console.log((new Date()) + ' Server is listening on port 3000');
});

//创建websocket服务器对象
wsServer = new WebSocketServer({
    httpServer: server,//配置刚刚创建的服务器
});
//websocket建立连接
wsServer.on('request', function(request) {
    //当前的连接  使用子协议
    // var connection = request.accept('echo-protocol', request.origin);
    var connection = request.accept(null, request.origin);//没有直接null
    connection.sendUTF('信息')//发送信息到客户端
    connection.on('message',function (msg) {
        connection.sendUTF(msg.utf8Data)
    })
});

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //创建websocket对象
        var socket=new WebSocket('ws://localhost:3000');
        //监听建立连接
        socket.onopen=function (res) {
            console.log('连接成功')
            console.log(res)
        }
        //监听消息
        socket.onmessage=function (data) {
            console.log('有消息来了')
            console.log(data.data)
        }
        function sendmsg(){
            var a=document.getElementById('inputid').value;
            socket.send(a)
        }
    </script>
</head>
<body>
<input type="text"id="inputid">
<input type="button"value="发送" onclick="sendmsg()">
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值