node创建服务器

创建websocket服务器

使用createserver创建,使用list监听ip地址和端口号

// websocket服务器创建
// 使用node 文件名开启服务器,使用ctri加c关闭
var websocket = require("nodejs-websocket");
var url = "https://mock.mengxuegu.com/mock/6141aa4b21805563ee1031d6/exam/slidenav";
// 使用createServer创建
websocket.createServer(function(ws) {
    // text接收客户端发来的数据
    ws.on("text", function(res) {
        console.log(res);
        // ws.send数据接受成功
        ws.send(url);
        setInterval(function() {
            ws.send(url);
        }, 5000000);
    })
    // error链接触发触发
    ws.on("error", function() {
        console.log("异常");
        // 触发异常的时候关闭
        ws.close();
    })
    // close断开链接时触发
    ws.on("close", function() {
        console.log("关闭");
    })
}).listen(8801, "127.0.0.1")
console.log("websocket服务器创建完成")

创建http服务器

// 搭建http服务器
var http = require("http");
var server = http.createServer(function(req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.end(JSON.stringify({ "name": "xiaoming" }));
    // 转化为字符串发送
})
server.listen(8888, "127.0.0.1");

使用form表单链接服务器

 <!-- 使用form表单链接服务器 -->
    <form action="http://127.0.0.1:8888">
        用户名:<input type="text"><input type="submit">
    </form>

使用ajax链接http服务器

  // http客户端
        $(function() {
            $.ajax({
                url: "http://127.0.0.1:8888",
                success: function(res) {
                    console.log(JSON.parse(res))
                        // 转化成对象接收
                }
            })
        })

使用ajax链接websocket服务器

 var websocket = new WebSocket("ws://127.0.0.1:8801");
        websocket.onopen = function() {
            console.log("成功");
            websocket.send("发送数据");
            websocket.onmessage = function(e) {
                $.ajax({
                    url: e.data,
                    type: "post",
                    datatype: "json",
                    success: function(res) {
                        console.log(res);
                    }
                })
            }
            websocket.onerror = function() {
                console.log("服务器端异常");
                websocket.close();
            }
            websocket.onclose = function() {
                console.log("服务器端关闭");
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值