美文网首页
Day01(node.js 与后台交互)

Day01(node.js 与后台交互)

作者: AnnQi | 来源:发表于2017-11-07 14:36 被阅读0次

index.js

var http = require("http");
var fs = require("fs");
var ws = require("nodejs-websocket");


http.createServer(function(req,res){ //(请求对象)
    fs.readFile(__dirname+req.url,function(err,data){// (错误对象,返回对象)
        res.writeHead(200,{"content-type":'text/html;cherset=utf-8'});
        res.end(data+"");   
    })
}).listen(3000); // 3000 http服务
console.log("listen 3000...");

var wsServer = ws.createServer(function(conn){
    console.log("有人链接");
    conn.on("text",function(str){
        console.log("收到:"+str);
        broadcast("你好,"+str);
    })
})
wsServer.listen(3002); //3002 websocket服务

function broadcast(msg){
    for(var i=0;i<wsServer.connections.length;i++){
        wsServer.connections[i].sendText(msg);
    }
}

a.html

<body>
        <input type="text" id="username" />
        <button id="btn">发送</button>
        <div id="box"></div>


        <script>
            var btn = document.getElementById("btn");
            var username = document.getElementById("username");
            var box = document.getElementById("box");
            var w = new WebSocket("ws://localhost:3002");
            btn.onclick = function(){
                w.send(username.value);
            }           
            w.onmessage = function(ev){
                var temp = document.createElement("p");
                temp.innerHTML = ev.data;
                box.appendChild(temp);
            }
        </script>
</body>

相关文章

网友评论

      本文标题:Day01(node.js 与后台交互)

      本文链接:https://www.haomeiwen.com/subject/tmwdmxtx.html