socket的运行步骤

在这之前用node.js的环境配置
1、在app.js中设置引入socket.io文件

var express = require('express');
var app = express();
var server = require('http').Server(app);(自己添加的)
var io = require('socket.io')(server);(自己添加的)

2、在index.html中写入输入框和要用的按钮

html代码片段
        
        
        
        
    js代码片段 var socket = io.connect('http://localhost:9000'); var username = "" btn2.onclick = function(){ username = info.value; socket.emit("login",username) info.value ="" } btn.onclick = function(){ socket.emit("info",info.value); info.value ="" } socket.on('msg', function (name,data) { var node = document.createElement("li") if(name == username){ node.style.textAlign = "right" } node.innerHTML = name+":"+data; ul.appendChild(node); });

    3、在app.js中监听并广播html发送过来的数据

    io.on('connection', function (socket) {
          socket.on("login",function(username){
            socket.name = username;
          });
    
           socket.on('info', function (data) {
            //console.log(data);
            io.emit("msg",socket.name,data)
          });
    });
    
    server.listen(9000);
    

    4、在cmd命令行中执行nodemon app.js
    在浏览器中打开localhost:9000

    你可能感兴趣的:(socket的运行步骤)